Skip to content

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

[feat]: openclaw-memory-plugin: 全面改进内存插件功能 (#479)

qin-ptr4f32d3a8a7ba
diff --git a/README_CN.md b/README_CN.md
index 88f4c23c3..c6923e9b7 100644
--- a/README_CN.md
+++ b/README_CN.md
@@ -16,6 +16,7 @@
[![][license-shield]][license-shield-link]
[![][last-commit-shield]][last-commit-shield-link]
+
👋 加入我们的社区
📱 <a href="./docs/en/about/01-about-us.md#lark-group">飞书群</a> · <a href="./docs/en/about/01-about-us.md#wechat-group">微信群</a> · <a href="https://discord.com/invite/eHvx8E9XF3">Discord</a> · <a href="https://x.com/openvikingai">X</a>
diff --git a/examples/openclaw-memory-plugin/INSTALL-AGENT.md b/examples/openclaw-memory-plugin/INSTALL-AGENT.md
new file mode 100644
index 000000000..220e60481
--- /dev/null
+++ b/examples/openclaw-memory-plugin/INSTALL-AGENT.md
@@ -0,0 +1,264 @@
+# OpenViking Memory Plugin — Agent Install Guide
+
+> For AI Agents (Claude Code, Cursor, etc.) to follow step-by-step.
+> Principle: auto-detect what you can; only ask the user when detection fails.
+
+---
+
+## Step 0: Choose Target OpenClaw Instance
+
+Check if the user has multiple OpenClaw instances:
+
+```bash
+ls -d ~/.openclaw* 2>/dev/null
+```
+
+If multiple directories exist (e.g. `~/.openclaw`, `~/.openclaw-openclaw-second`), ask the user which instance to install to. Pass the chosen directory via `--workdir`:
+
+```bash
+npx ./examples/openclaw-memory-plugin/setup-helper --workdir ~/.openclaw-openclaw-second
+```
+
+If only `~/.openclaw` exists, proceed with the default.
+
+## Step 1: Choose Deployment Mode
+
+Ask the user: "How do you want to use OpenViking?"
+
+- **A) Local** — Run OpenViking on this machine (requires Python >= 3.10)
+- **B) Remote** — Connect to an existing OpenViking server (only needs the server URL and API Key)
+
+→ A: Go to [Local Deployment Path](#local-deployment-path)
+→ B: Go to [Remote Connection Path](#remote-connection-path)
+
+---
+
+## Local Deployment Path
+
+### Step L1: Check Environment
+
+Run each check. Every check must pass before continuing.
+
+**1. Python**
+
+```bash
+python3 --version
+```
+
+- Pass: >= 3.10
+- Fail: Tell user "Python >= 3.10 is required. Install from https://www.python.org/downloads/"
+- Multiple versions: Ask user which Python path to use
+
+**2. Node.js**
+
+```bash
+node -v
+```
+
+- Pass: >= v22
+- Fail: Tell user "Node.js >= 22 is required. Install from https://nodejs.org/"
+
+**3. OpenClaw**
+
+```bash
+openclaw --version
+```
+
+- Pass: Version output present
+- Fail: Tell user to run `npm install -g openclaw && openclaw onboard`
+
+### Step L2: Install OpenViking
+
+```bash
+python3 -m pip install openviking --upgrade
+```
+
+- Pass: Continue
+- Fail with `externally-managed`:
+ ```bash
+ python3 -m venv ~/.openviking/venv
+ ~/.openviking/venv/bin/pip install openviking --upgrade
+ ```
+ Set `OPENVIKING_PYTHON=~/.openviking/venv/bin/python` for later steps
+- Fail with `No matching distribution`: Python is below 3.10, tell user to upgrade
+- Other failure: Print full error, ask user
+
+Verify:
+
+```bash
+python3 -c "import openviking; print('ok')"
+```
+
+### Step L3: Configure
+
+Check if `~/.openviking/ov.conf` already exists:
+
+- **Exists**: Ask user "Found existing config at ~/.openviking/ov.conf. Keep it?"
+ - Yes: Skip to Step L4
+ - No: Continue with configuration below
+
+- **Does not exist**: Collect configuration
+
+**Ask user for API Key:**
+
+> "Please provide your Volcengine Ark API Key (used for Embedding and VLM model calls).
+> Get one at https://console.volcengine.com/ark if you don't have one."
+
+Check if the OpenViking repo is available locally:
+
+```bash
+ls examples/openclaw-memory-plugin/setup-helper/package.json 2>/dev/null
+```
+
+- In repo: Run setup helper directly
+- Not in repo: Clone first
+
+```bash
+git clone https://github.com/volcengine/OpenViking.git /tmp/OpenViking
+cd /tmp/OpenViking
+```
+
+Run the setup helper:
+
+```bash
+npx ./examples/openclaw-memory-plugin/setup-helper
+```
+
+At the interactive prompts:
+- Workspace: Press Enter for default path
+- API Key: Enter the user's key
+- VLM model: Press Enter for default `doubao-seed-2-0-pro-260215`
+- Embedding model: Press Enter for default `doubao-embedding-vision-251215`
+- Ports: Press Enter for default 1933/1833
+
+Wait for `Setup complete!`
+
+### Step L4: Start and Verify
+
+```bash
+source ~/.openclaw/openviking.env && openclaw gateway
+```
+
+- Pass: Output contains `memory-openviking: local server started`
+- Fail with `port occupied`:
+ The port is used by another process. Change port:
+ ```bash
+ openclaw config set plugins.entries.memory-openviking.config.port 1934
+ source ~/.openclaw/openviking.env && openclaw gateway
+ ```
+- Fail with `subprocess exited`: Check stderr for Python errors — usually wrong API Key or openviking not installed properly
+
+Verify:
+
+```bash
+openclaw status
+```
+
+Memory line should show `enabled (plugin memory-openviking)`.
+
+Tell user: "OpenViking memory is active. I'll automatically remember important facts from our conversations and recall them when relevant."
+
+---
+
+## Remote Connection Path
+
+### Step R1: Collect Connection Info
+
+Ask user for:
+
+1. **OpenViking server URL** (e.g. `http://10.0.0.1:1933`)
+ > This is the OpenViking HTTP API address.
+
+2. **OpenViking API Key** (optional)
+ > Required if the server has `root_api_key` configured. This authenticates to the OpenViking server — it is NOT a Volcengine Ark API Key.
+
+### Step R2: Check Environment
+
+**1. Node.js**
+
+```bash
+node -v
+```
+
+- Pass: >= v22
+- Fail: Tell user to install Node.js >= 22
+
+**2. OpenClaw**
+
+```bash
+openclaw --version
+```
+
+- Pass: Version output present
+- Fail: `npm install -g openclaw && openclaw onboard`
+
+> Remote mode does **not** require Python — OpenViking runs on the remote server.
+
+### Step R3: Deploy Plugin and Configure
+
+Get the plugin code:
+
+```bash
+git clone https://github.com/volcengine/OpenViking.git /tmp/OpenViking
+cd /tmp/OpenViking/examples/openclaw-memory-plugin
+npm install
+openclaw plugin link .
+```
+
+Configure remote connection (substitute user-provided values). If targeting a non-default instance, prefix each command with `OPENCLAW_STATE_DIR=<workdir>`:
+
+```bash
+openclaw config set plugins.enabled true --json
+openclaw config set plugins.slots.memory memory-openviking
+openclaw config set plugins.entries.memory-openviking.config.mode remote
+openclaw config set plugins.entries.memory-openviking.config.baseUrl "<user's server URL>"
+openclaw config set plugins.entries.memory-openviking.config.apiKey "<user's API Key>"
+openclaw config set plugins.entries.memory-openviking.config.autoRecall true --json
+openclaw config set plugins.entries.memory-openviking.config.autoCapture true --json
+```
+
+If user has no API Key (server auth not enabled), skip the apiKey line.
+
+### Step R4: Start and Verify
+
+```bash
+openclaw gateway
+```
+
+- Pass: Output contains `memory-openviking: initialized`
+- Fail with connection error: Verify server is reachable — `curl <baseUrl>/health` should return `{"status":"ok"}`
+
+```bash
+openclaw status
+```
+
+Memory line should show `enabled (plugin memory-openviking)`.
+
+Tell user: "OpenViking memory is connected to the remote server. I'll automatically remember important facts and recall them when relevant."
+
+---
+
+## Field Reference
+
+| Field | Meaning | Required For |
+|-------|---------|-------------|
+| Volcengine Ark API Key | Embedding + VLM model access | Local |
+| OpenViking API Key | Server authentication key | Remote (if server has auth enabled) |
+| agentId | Identifies this agent to OpenViking | Both (auto-generated if not set) |
+| baseUrl | OpenViking HTTP address | Remote |
+| workspace | Data storage directory | Local |
+| server port | OpenViking HTTP port (default 1933) | Local |
+| VLM model | Memory extraction model | Local |
+| Embedding model | Text vectorization model | Local |
+
+---
+
+## Troubleshooting
+
+| Error | Cause | Fix |
+|-------|-------|-----|
+| `port occupied` | Port used by another process | Change port in config, e.g. `openclaw config set plugins.entries.memory-openviking.config.port 1934` |
+| `extracted 0 memories` | Wrong API Key or model name | Check `api_key` and `model` in `~/.openviking/ov.conf` |
+| `externally-managed-environment` | Python PEP 668 restriction | Install via venv |
+| `ECONNREFUSED` | Remote server unreachable | Verify baseUrl and network connectivity |
+| Plugin not loaded | Env file not sourced | `source ~/.openclaw/openviking.env` (local mode) |
diff --git a/examples/openclaw-memory-plugin/INSTALL-ZH.md b/examples/openclaw-memory-plugin/INSTALL-ZH.md
index 6dfa6111c..58a53b937 100644
--- a/examples/openclaw-memory-plugin/INSTALL-ZH.md
+++ b/examples/openclaw-memory-plugin/INSTALL-ZH.md
@@ -6,8 +6,6 @@
## 一键安装(Linux / macOS)
-**前置条件:** Python >= 3.10、Node.js >= 22。脚本会自动校验这些依赖,若有缺失会给出安装指引。
-
```bash
curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-memory-plugin/install.sh | bash
```
@@ -18,419 +16,124 @@ curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples
curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-memory-plugin/install.sh | bash -s -y
```
-脚本会:1) 校验 OpenViking 运行环境(并检查是否已安装 OpenClaw);2) 仅安装 OpenViking;3) 配置并部署记忆插件。
-
----
-
-## 一、快速开始(让 OpenClaw 自动安装)
-
-先将技能文件复制到 OpenClaw 技能目录,再让 OpenClaw 完成后续步骤:
-
-**Linux / macOS:**
+安装到指定 OpenClaw 实例:
```bash
-mkdir -p ~/.openclaw/skills/install-openviking-memory
-cp examples/openclaw-memory-plugin/skills/install-openviking-memory/SKILL.md \
- ~/.openclaw/skills/install-openviking-memory/
-```
-
-**Windows (cmd):**
-
-```cmd
-mkdir "%USERPROFILE%\.openclaw\skills\install-openviking-memory"
-copy examples\openclaw-memory-plugin\skills\install-openviking-memory\SKILL.md ^
- "%USERPROFILE%\.openclaw\skills\install-openviking-memory\"
+curl -fsSL ... | bash -s -- --workdir ~/.openclaw-openclaw-second
```
-然后对 OpenClaw 说:**「安装 OpenViking 记忆」** — 它会读取技能并自动完成安装。
-
-如需手动安装,请继续阅读。
+脚本会自动检测多个 OpenClaw 实例并让你选择。还会提示选择 local/remote 模式——remote 模式连接远端 OpenViking 服务,不需要安装 Python。
---
-## 二、环境要求
-
-### 总览
-
-| 组件 | 版本要求 | 用途 | 必需? |
-|------|----------|------|--------|
-| **Python** | >= 3.10 | OpenViking 运行时 | 是 |
-| **Node.js** | >= 22 | OpenClaw 运行时 + 安装助手 | 是 |
-| **cmake** | — | 编译 C++ 扩展(OpenViking + OpenClaw 的 node-llama-cpp) | 是 |
-| **g++ (gcc-c++)** | — | C++ 编译器 | 是 |
-| **Go** | >= 1.19 | 编译 AGFS 服务端(仅 Linux 源码安装) | 源码安装必需 |
-| **火山引擎 Ark API Key** | — | Embedding + VLM 模型调用 | 是 |
+## 前置条件
-> **PyPI 安装 vs 源码安装:**
-> - `pip install openviking --upgrade --force-reinstall`(PyPI 预编译包):只需 Python、cmake、g++,**不需要 Go**
-> - `pip install -e . --force-reinstall`(源码安装):需要 Python、cmake、g++ **以及 Go >= 1.19**(Linux 上编译 AGFS)
-> - **Windows** 用户可直接使用预编译 wheel 包,无需 Go
+| 组件 | 版本要求 | 用途 |
+|------|----------|------|
+| **Python** | >= 3.10 | OpenViking 运行时 |
+| **Node.js** | >= 22 | OpenClaw 运行时 |
+| **火山引擎 Ark API Key** | — | Embedding + VLM 模型调用 |
-### 快速检查
+快速检查:
```bash
-python3 --version # >= 3.10
-node -v # >= v22
-cmake --version # 已安装
-g++ --version # 已安装
-go version # >= go1.25(源码安装需要)
+python3 --version # >= 3.10
+node -v # >= v22
+openclaw --version # 已安装
```
-如果以上命令均正常,可跳过"环境准备"直接进入[第三节:安装步骤](#三安装步骤)。
+- Python: https://www.python.org/downloads/
+- Node.js: https://nodejs.org/
+- OpenClaw: `npm install -g openclaw && openclaw onboard`
---
-## 三、环境准备(Linux)
+## 方式一:本地部署(推荐)
-> 如果你的系统已满足上述环境要求,可跳过此节。
+在本机启动 OpenViking 服务,适合个人使用。
-### 3.1 安装编译工具
-
-> 已安装?运行 `cmake --version && g++ --version`,如果都有输出则跳过此步。
-
-**RHEL / CentOS / openEuler / Fedora:**
+### Step 1: 安装 OpenViking
```bash
-sudo dnf install -y gcc gcc-c++ cmake make
+python3 -m pip install openviking --upgrade
```
-**Ubuntu / Debian:**
-
-```bash
-sudo apt update
-sudo apt install -y build-essential cmake
-```
-
-### 3.2 安装 Python 3.10+
-
-> 已安装?运行 `python3 --version`,如果显示 >= 3.10 则跳过此步。
-
-许多 Linux 发行版(如 openEuler 22.03、CentOS 7/8)自带 Python 3.9 或更低版本,且软件仓库中往往没有 Python 3.10+ 的包。推荐从源码编译。
-
-#### 方式一:从源码编译(推荐)
-
-```bash
-# 1. 安装编译依赖
-# RHEL / CentOS / openEuler / Fedora:
-sudo dnf install -y gcc make openssl-devel bzip2-devel libffi-devel \
- zlib-devel readline-devel sqlite-devel xz-devel tk-devel
-
-# Ubuntu / Debian:
-# sudo apt install -y build-essential libssl-dev libbz2-dev libffi-dev \
-# zlib1g-dev libreadline-dev libsqlite3-dev liblzma-dev tk-dev
-
-# 2. 下载并编译
-cd /tmp
-curl -O https://www.python.org/ftp/python/3.11.12/Python-3.11.12.tgz
-tar xzf Python-3.11.12.tgz
-cd Python-3.11.12
-./configure --prefix=/usr/local --enable-optimizations --enable-shared \
- LDFLAGS="-Wl,-rpath /usr/local/lib"
-make -j$(nproc)
-sudo make altinstall
-
-# 3. 创建软链接,使 python3 / pip3 指向新版本
-sudo ln -sf /usr/local/bin/python3.11 /usr/local/bin/python3
-sudo ln -sf /usr/local/bin/pip3.11 /usr/local/bin/pip3
-
-# 4. 验证
-python3 --version # 确认 >= 3.10 即可
-```
-
-> **提示:** 使用 `altinstall` 而非 `install`,避免覆盖系统默认 Python。`/usr/local/bin` 在 `PATH` 中通常优先于 `/usr/bin`,创建软链接后 `python3` 即指向新版本。
-
-#### 方式二:通过包管理器安装(部分发行版可用)
-
-```bash
-# RHEL / CentOS / openEuler / Fedora(不一定可用)
-sudo dnf install -y python3.11 python3.11-devel python3.11-pip
-
-# Ubuntu 22.04+ 自带 Python 3.10
-sudo apt install -y python3 python3-dev python3-pip python3-venv
-
-# Ubuntu 20.04 或更旧版本,需添加 PPA
-sudo add-apt-repository ppa:deadsnakes/ppa
-sudo apt install -y python3.11 python3.11-dev python3.11-venv
-```
+验证:`python3 -c "import openviking; print('ok')"`
-> 如果 `dnf install python3.11` 报 `No match for argument`,说明仓库中没有该包,请使用源码编译方式。
+> 遇到 `externally-managed-environment`?使用一键安装脚本(自动处理 venv)或手动创建:
+> `python3 -m venv ~/.openviking/venv && ~/.openviking/venv/bin/pip install openviking`
-安装完成后升级 pip:
-
-```bash
-python3 -m pip install --upgrade pip
-```
-
-> 下载 Python 包较慢?参见[附录:网络加速](#七网络加速镜像与代理配置)配置 pip 镜像。
-
-### 3.3 安装 Node.js >= 22
-
-> 已安装?运行 `node -v`,如果显示 >= v22 则跳过此步。
-
-OpenClaw 要求 Node.js >= 22。安装助手脚本也依赖 Node.js 运行。
-
-#### 方式一:通过 NodeSource 安装(推荐)
-
-```bash
-# RHEL / CentOS / openEuler / Fedora
-curl -fsSL https://rpm.nodesource.com/setup_22.x | sudo bash -
-sudo dnf install -y nodejs
-
-# Ubuntu / Debian
-# curl -fsSL https://deb.nodesource.com/setup_22.x | sudo bash -
-# sudo apt install -y nodejs
-```
-
-#### 方式二:通过 nvm 安装(无需 root 权限)
-
-```bash
-curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash
-source ~/.bashrc
-nvm install 22
-nvm use 22
-```
-
-#### 方式三:手动下载二进制包
-
-```bash
-wget https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-x64.tar.xz
-sudo tar -C /usr/local -xJf node-v22.14.0-linux-x64.tar.xz
-echo 'export PATH=$PATH:/usr/local/node-v22.14.0-linux-x64/bin' >> ~/.bashrc
-source ~/.bashrc
-```
-
-> ARM 架构请将 `linux-x64` 替换为 `linux-arm64`。
-
-验证:
-
-```bash
-node -v # >= v22
-npm -v
-```
-
-### 3.4 安装 Go >= 1.25(仅源码安装需要)
-
-> 已安装?运行 `go version`,如果显示 >= go1.25 则跳过此步。
-> 使用 `pip install openviking --upgrade --force-reinstall`(PyPI 预编译包)的用户也可跳过。
-
-Linux 源码安装 OpenViking 时需要 Go 编译 AGFS 服务端。
-
-```bash
-# 下载(ARM 请替换为 go1.25.6.linux-arm64.tar.gz)
-wget https://go.dev/dl/go1.25.6.linux-amd64.tar.gz
-
-# 解压
-sudo rm -rf /usr/local/go
-sudo tar -C /usr/local -xzf go1.25.6.linux-amd64.tar.gz
-
-# 配置环境变量
-cat >> ~/.bashrc << 'EOF'
-export GOROOT=/usr/local/go
-export GOPATH=$HOME/go
-export PATH=$PATH:$GOROOT/bin:$GOPATH/bin
-EOF
-source ~/.bashrc
-
-# 验证
-go version # >= go1.25
-```
-
-> Go 模块下载慢?参见[附录:网络加速](#七网络加速镜像与代理配置)配置 GOPROXY。
-
-### 3.5 验证环境就绪
-
-```bash
-python3 --version # >= 3.10
-node -v # >= v22
-cmake --version # 已安装
-g++ --version # 已安装
-go version # >= go1.25(源码安装需要)
-```
-
-全部通过后即可开始安装。
-
----
-
-## 四、安装步骤
-
-### 4.1 安装 OpenClaw
-
-> **前置条件:** cmake 和 g++ 必须已安装(OpenClaw 依赖 `node-llama-cpp`,安装时需编译 C++ 代码)。
-
-```bash
-npm install -g openclaw
-```
-
-> 下载慢?参见[附录:网络加速](#七网络加速镜像与代理配置)配置 npm 镜像。
-
-运行引导程序配置 LLM:
-
-```bash
-openclaw onboard
-```
-
-验证:
-
-```bash
-openclaw --version
-```
-
-### 4.2 安装 OpenViking
+### Step 2: 运行安装助手
```bash
git clone https://github.com/volcengine/OpenViking.git
cd OpenViking
-```
-
-#### 方式 A:从 PyPI 安装(推荐,无需 Go)
-
-```bash
-python3 -m pip install openviking --upgrade --force-reinstall
-```
-
-#### 方式 B:从源码安装(开发者模式,需要 Go)
-
-**Linux / macOS:**
-
-```bash
-go version && cmake --version && g++ --version # 确认工具已安装
-python3 -m pip install -e .
-```
-
-**Windows:**
-
-```powershell
-python -m pip install -e .
-```
-
-> **提示:** Linux 源码安装**必须**安装 Go >= 1.25(编译 AGFS)。如确需跳过(高级用户):
-> ```bash
-> OPENVIKING_SKIP_AGFS_BUILD=1 python3 -m pip install -e .
-> ```
-
-验证:
-
-```bash
-python3 -c "import openviking; print('ok')"
-```
-
-### 4.3 运行安装助手
-
-在 OpenViking 仓库根目录下执行:
-
-```bash
npx ./examples/openclaw-memory-plugin/setup-helper
```
-安装助手会依次完成:
-
-1. **环境检查** — 校验 cmake、g++、Python、Go、OpenClaw 是否就绪
-2. **安装 OpenViking**(如尚未安装)
-3. **交互配置** — 提示输入以下信息:
- - 数据存储路径(默认为绝对路径,如 `/home/yourname/.openviking/data`)
- - 火山引擎 Ark API Key
- - VLM 模型名称(默认 `doubao-seed-2-0-pro-260215`)
- - Embedding 模型名称(默认 `doubao-embedding-vision-250615`)
- - 服务端口(默认 1933 / 1833)
-4. **生成配置** — 创建 `~/.openviking/ov.conf`
-5. **部署插件** — 将 `memory-openviking` 注册到 OpenClaw
-6. **写入环境文件** — 生成 `~/.openclaw/openviking.env`
-
-> 非交互模式:`npx ./examples/openclaw-memory-plugin/setup-helper -y`
+安装助手会提示输入 Ark API Key 并自动生成配置文件。
-### 4.4 启动并验证
-
-**Linux / macOS:**
+### Step 3: 启动
```bash
source ~/.openclaw/openviking.env && openclaw gateway
```
-**Windows (cmd):**
-
-```cmd
-call "%USERPROFILE%\.openclaw\openviking.env.bat" && openclaw gateway
-```
+看到 `memory-openviking: local server started` 表示成功。
-看到以下输出表示安装成功:
-
-```
-[gateway] listening on ws://127.0.0.1:18789
-[gateway] memory-openviking: local server started (http://127.0.0.1:1933, config: ...)
-```
-
-检查插件状态:
+### Step 4: 验证
```bash
openclaw status
# Memory 行应显示:enabled (plugin memory-openviking)
```
-测试记忆功能:
-
-```bash
-openclaw tui
-```
-
-输入:「请记住:我最喜欢的编程语言是 Python。」
-
-在新对话中问:「我最喜欢的编程语言是什么?」
-
-OpenClaw 应能从记忆中回忆并回答。
-
---
-## 五、日常使用
-
-每次使用带记忆功能的 OpenClaw:
-
-**Linux / macOS:**
-
-```bash
-source ~/.openclaw/openviking.env && openclaw gateway
-```
-
-**Windows (cmd):**
-
-```cmd
-call "%USERPROFILE%\.openclaw\openviking.env.bat" && openclaw gateway
-```
+## 方式二:连接远端 OpenViking
-> **便捷方式(Linux/macOS):** 加入 `~/.bashrc`:
-> ```bash
-> alias openclaw-start='source ~/.openclaw/openviking.env && openclaw gateway'
-> ```
+已有运行中的 OpenViking 服务?只需配置 OpenClaw 插件指向远端,**不需要安装 Python / OpenViking**。
-### 5.1 启用或关闭记忆插件
+**前置:** 已有 OpenViking 服务地址 + API Key(如服务端启用了认证)。
-关闭 OpenViking 记忆插件:
+### Step 1: 部署插件代码
```bash
-openclaw config set plugins.slots.memory none
+git clone https://github.com/volcengine/OpenViking.git
+cd OpenViking/examples/openclaw-memory-plugin
+npm install
+openclaw plugin link .
```
-启用 OpenViking 记忆插件:
+### Step 2: 配置远端连接
```bash
+openclaw config set plugins.enabled true --json
openclaw config set plugins.slots.memory memory-openviking
+openclaw config set plugins.entries.memory-openviking.config.mode remote
+openclaw config set plugins.entries.memory-openviking.config.baseUrl "http://your-server:1933"
+openclaw config set plugins.entries.memory-openviking.config.apiKey "your-api-key"
+openclaw config set plugins.entries.memory-openviking.config.autoRecall true --json
+openclaw config set plugins.entries.memory-openviking.config.autoCapture true --json
```
-如果 gateway 已在运行,修改 slot 后请重启 gateway 使配置生效。
+### Step 3: 启动并验证
-插件会自动启动和停止 OpenViking 服务。
+```bash
+openclaw gateway
+openclaw status
+```
---
-## 六、配置参考
+## 配置参考
-### `~/.openviking/ov.conf`
+### `~/.openviking/ov.conf`(本地模式)
```json
{
- "server": {
- "host": "127.0.0.1",
- "port": 1933
- },
+ "root_api_key": null,
+ "server": { "host": "127.0.0.1", "port": 1933 },
"storage": {
"workspace": "/home/yourname/.openviking/data",
"vectordb": { "backend": "local" },
@@ -438,305 +141,83 @@ openclaw config set plugins.slots.memory memory-openviking
},
"embedding": {
"dense": {
- "backend": "volcengine",
- "api_key": "<your-api-key>",
- "model": "doubao-embedding-vision-250615",
+ "provider": "volcengine",
+ "api_key": "<your-ark-api-key>",
+ "model": "doubao-embedding-vision-251215",
"api_base": "https://ark.cn-beijing.volces.com/api/v3",
"dimension": 1024,
"input": "multimodal"
}
},
"vlm": {
- "backend": "volcengine",
- "api_key": "<your-api-key>",
+ "provider": "volcengine",
+ "api_key": "<your-ark-api-key>",
"model": "doubao-seed-2-0-pro-260215",
- "api_base": "https://ark.cn-beijing.volces.com/api/v3",
- "temperature": 0.1,
- "max_retries": 3
+ "api_base": "https://ark.cn-beijing.volces.com/api/v3"
}
}
```
-> **注意:** `workspace` 必须使用**绝对路径**(如 `/home/yourname/.openviking/data`),不支持 `~` 或相对路径。安装助手会自动获取并填入。
-
-### `~/.openclaw/openviking.env`
-
-由安装助手自动生成:
+> `root_api_key`:设置后,所有 HTTP 请求须携带 `X-API-Key` 头。本地模式默认为 `null`(不启用认证)。
-```bash
-export OPENVIKING_PYTHON='/usr/local/bin/python3'
-export OPENVIKING_GO_PATH='/usr/local/go/bin' # 可选
-```
+### `agentId` 配置(插件配置)
-Windows 版(`openviking.env.bat`):
+通过 `X-OpenViking-Agent` header 传给服务端的 Agent 标识,用于区分不同的 OpenClaw 实例。
-```cmd
-set OPENVIKING_PYTHON=C:\path\to\python.exe
-set OPENVIKING_GO_PATH=C:\path\to\go\bin
-```
-
-### 安装助手选项
-
-```
-npx ./examples/openclaw-memory-plugin/setup-helper [选项]
-
- -y, --yes 非交互模式,使用默认值
- -h, --help 显示帮助
-
-环境变量:
- OPENVIKING_PYTHON Python 解释器路径
- OPENVIKING_CONFIG_FILE 自定义 ov.conf 路径
- OPENVIKING_REPO 本地仓库路径(在仓库内运行时自动检测)
- OPENVIKING_ARK_API_KEY 跳过 API Key 提示(用于 CI/脚本)
-```
-
----
-
-## 七、常见问题
-
-### 安装阶段
-
-#### Q: `cmake not found` / `g++ not found`(安装 OpenClaw 或 OpenViking 时)
-
-OpenClaw 依赖 `node-llama-cpp`(需编译 C++),OpenViking 的 C++ 扩展也需要 cmake/g++。
-
-```bash
-# RHEL / CentOS / openEuler
-sudo dnf install -y gcc gcc-c++ cmake make
-
-# Ubuntu / Debian
-sudo apt install -y build-essential cmake
-```
-
-#### Q: `No matching distribution found for python-multipart>=0.0.22`
-
-pip 使用了 Python 3.9 解释器。请确认使用 Python 3.10+:
-
-```bash
-python3 --version # 确认 >= 3.10
-python3 -m pip install -e .
-```
-
-#### Q: `fatal error: Python.h: No such file or directory`
-
-缺少 Python 开发头文件:
+自定义方式:
```bash
-# RHEL / CentOS / openEuler
-sudo dnf install -y python3-devel # 或 python3.11-devel
-
-# Ubuntu / Debian
-sudo apt install -y python3-dev # 或 python3.11-dev
+# 在插件配置中指定
+openclaw config set plugins.entries.memory-openviking.config.agentId "my-agent"
```
-> 如果是源码编译的 Python,开发头文件已包含在内,无需额外安装。
-
-#### Q: `Go compiler not found` / AGFS 构建失败
-
-Linux 源码安装**必须**安装 Go >= 1.25,参见 [3.4 安装 Go](#34-安装-go--125仅源码安装需要)。
-
-```bash
-go version # 确认 >= 1.19
-python3 -m pip install -e .
-```
+如果未配置,插件会自动生成一个随机唯一的 ID(格式:`openclaw-<hostname>-<random>`)。
-#### Q: Go 模块下载超时(`dial tcp: i/o timeout`)
-
-配置 Go 代理,参见[附录:网络加速](#七网络加速镜像与代理配置)。
-
-#### Q: npm 安装报 `ERR_INVALID_URL`
-
-通常是代理环境变量格式错误。代理地址**必须**包含 `http://` 前缀:
-
-```bash
-# 错误
-export https_proxy=192.168.1.1:7897
-
-# 正确
-export https_proxy=http://192.168.1.1:7897
-```
-
-或清除代理:
-
-```bash
-unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY
-```
-
-#### Q: npm 安装报 `ENOTEMPTY`
+### `~/.openclaw/openviking.env`
-上次安装中断留下残留文件,清理后重试:
+由安装助手自动生成,记录 Python 路径等环境变量:
```bash
-rm -rf $(npm root -g)/openclaw $(npm root -g)/.openclaw-*
-npm install -g openclaw
+export OPENVIKING_PYTHON='/usr/local/bin/python3'
```
-### 运行阶段
-
-#### Q: 网关输出中看不到 `memory-openviking` 插件
-
-- 是否在 `openclaw gateway` 之前加载了环境变量?
- - Linux/macOS:`source ~/.openclaw/openviking.env`
- - Windows:`call "%USERPROFILE%\.openclaw\openviking.env.bat"`
-- 运行 `openclaw status` 检查插件状态
-- 重新执行安装助手:`npx ./examples/openclaw-memory-plugin/setup-helper`
-
-#### Q: `health check timeout at http://127.0.0.1:1933`
+---
-端口被旧进程占用,清理后重启:
+## 日常使用
```bash
-# Linux / macOS
-lsof -ti tcp:1933 tcp:1833 | xargs kill -9
+# 启动
source ~/.openclaw/openviking.env && openclaw gateway
-```
-
-```cmd
-REM Windows
-for /f "tokens=5" %a in ('netstat -ano ^| findstr "LISTENING" ^| findstr ":1933 :1833"') do taskkill /PID %a /F
-call "%USERPROFILE%\.openclaw\openviking.env.bat" && openclaw gateway
-```
-
-#### Q: `extracted 0 memories`
-`ov.conf` 中的模型配置有误,请检查:
-
-- `embedding.dense.api_key` 为有效的火山引擎 Ark API Key
-- `vlm.api_key` 已设置(通常与 embedding 相同)
-- `vlm.model` 为模型名称(如 `doubao-seed-2-0-pro-260215`),**不是** API Key
-
-### Python 版本问题
-
-#### Q: `TypeError: unsupported operand type(s) for |: 'type' and 'NoneType'`
-
-Python 版本低于 3.10(`X | None` 语法是 3.10 引入的),需升级 Python,参见 [3.2 安装 Python](#32-安装-python-310)。
-
-#### Q: `pip install -e .` 安装到了错误的 Python
-
-使用显式路径指定 Python:
+# 关闭记忆
+openclaw config set plugins.slots.memory none
-```bash
-python3.11 -m pip install -e .
-export OPENVIKING_PYTHON=python3.11
-npx ./examples/openclaw-memory-plugin/setup-helper
+# 开启记忆
+openclaw config set plugins.slots.memory memory-openviking
```
-#### Q: 报错 `externally-managed-environment` / `This environment is externally managed`
-
-Ubuntu、Debian 等系统的 Python 受 PEP 668 保护,不允许直接用 `pip` 安装到系统环境。可选做法:
-
-1. **推荐**:使用本仓库的一键安装脚本,脚本会尝试用 venv/virtualenv 在 `~/.openviking/venv` 安装;若系统没有 venv,会提示安装对应版本的包。
- ```bash
- curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-memory-plugin/install.sh | bash
- ```
-
-2. **安装 venv**:请使用与当前 Python 版本一致的包(很多系统没有 `python3-venv` 只有版本号包):
- ```bash
- python3 --version # 例如 Python 3.12.x
- sudo apt install -y python3.12-venv # 把 3.12 换成你的版本;或试 python3-full
- ```
- 然后重新执行上述 curl 安装命令。
-
-3. **无法安装 venv 时**(如部分云镜像无 python3.x-venv):允许安装到系统(不推荐,可能影响系统 Python):
- ```bash
- OPENVIKING_ALLOW_BREAK_SYSTEM_PACKAGES=1 curl -fsSL .../install.sh | bash
- ```
-
-4. 手动创建虚拟环境并安装:
- ```bash
- sudo apt install -y python3.12-venv # 版本号与 python3 --version 一致
- python3 -m venv ~/.openviking/venv
- ~/.openviking/venv/bin/pip install openviking
- export OPENVIKING_PYTHON=~/.openviking/venv/bin/python
- ```
-
---
-## 八、网络加速(镜像与代理配置)
-
-> 以下配置适用于下载速度较慢的网络环境。
-
-### pip 镜像
-
-```bash
-# 永久配置(推荐)
-python3 -m pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
-python3 -m pip config set global.trusted-host pypi.tuna.tsinghua.edu.cn
-
-# 其他可选镜像
-# 阿里云:https://mirrors.aliyun.com/pypi/simple/
-# 华为云:https://repo.huaweicloud.com/repository/pypi/simple/
-# 腾讯云:https://mirrors.cloud.tencent.com/pypi/simple/
-```
-
-单次安装时临时指定:
-
-```bash
-python3 -m pip install openviking --upgrade --force-reinstall -i https://pypi.tuna.tsinghua.edu.cn/simple
-```
-
-### npm 镜像
-
-```bash
-# 永久配置(推荐)
-npm config set registry https://registry.npmmirror.com
-
-# 单次指定
-npm install -g openclaw --registry=https://registry.npmmirror.com
-```
-
-### Go 代理
-
-```bash
-# 七牛云(推荐)
-go env -w GOPROXY=https://goproxy.cn,direct
-
-# 阿里云
-# go env -w GOPROXY=https://mirrors.aliyun.com/goproxy/,direct
+## 常见问题
-# 关闭校验(部分私有模块可能需要)
-go env -w GONOSUMCHECK=*
-
-# 验证
-go env GOPROXY
-```
-
-> 配置后全局生效,后续 `pip install -e .` 编译 AGFS 时会自动使用。
+| 症状 | 原因 | 修复 |
+|------|------|------|
+| `port occupied` | 端口被其他进程占用 | 换端口:`openclaw config set plugins.entries.memory-openviking.config.port 1934` |
+| `extracted 0 memories` | API Key 或模型名配置错误 | 检查 `ov.conf` 中 `api_key` 和 `model` 字段 |
+| 插件未加载 | 未加载环境变量 | 启动前执行 `source ~/.openclaw/openviking.env` |
+| `externally-managed-environment` | Python PEP 668 限制 | 使用 venv 或一键安装脚本 |
+| `TypeError: unsupported operand type(s) for \|` | Python < 3.10 | 升级 Python 至 3.10+ |
---
-## 九、卸载
-
-**Linux / macOS:**
+## 卸载
```bash
-# 停止服务
lsof -ti tcp:1933 tcp:1833 tcp:18789 | xargs kill -9
-
-# 卸载 OpenClaw
-npm uninstall -g openclaw
-rm -rf ~/.openclaw
-
-# 卸载 OpenViking
-python3 -m pip uninstall openviking -y
-rm -rf ~/.openviking
-```
-
-**Windows (cmd):**
-
-```cmd
-REM 停止服务
-for /f "tokens=5" %a in ('netstat -ano ^| findstr "LISTENING" ^| findstr ":1933 :1833 :18789"') do taskkill /PID %a /F
-
-REM 卸载 OpenClaw
-npm uninstall -g openclaw
-rmdir /s /q "%USERPROFILE%\.openclaw"
-
-REM 卸载 OpenViking
-python -m pip uninstall openviking -y
-rmdir /s /q "%USERPROFILE%\.openviking"
+npm uninstall -g openclaw && rm -rf ~/.openclaw
+python3 -m pip uninstall openviking -y && rm -rf ~/.openviking
```
---
-**另见:** [INSTALL.md](./INSTALL.md)(English version)
+**另见:** [INSTALL.md](./INSTALL.md)(English) · [INSTALL-AGENT.md](./INSTALL-AGENT.md)(Agent Install Guide)
diff --git a/examples/openclaw-memory-plugin/INSTALL.md b/examples/openclaw-memory-plugin/INSTALL.md
index f3c0a7b56..0907e5dbc 100644
--- a/examples/openclaw-memory-plugin/INSTALL.md
+++ b/examples/openclaw-memory-plugin/INSTALL.md
@@ -18,7 +18,20 @@ Non-interactive mode:
curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/openclaw-memory-plugin/install.sh | bash -s -y
```
-The script will: 1) validate the OpenViking runtime environment (and check that OpenClaw is installed), 2) install OpenViking only, 3) configure and deploy the memory plugin.
+Install to a specific OpenClaw instance:
+
+```bash
+curl -fsSL ... | bash -s -- --workdir ~/.openclaw-openclaw-second
+```
+
+Remote mode (connect to an existing OpenViking server, no Python/OpenViking required):
+
+```bash
+# The script will prompt for mode selection (local/remote)
+curl -fsSL ... | bash
+```
+
+The script will: 1) select target OpenClaw instance (auto-detects multiple instances), 2) select mode (local/remote), 3) validate environment and install (local mode), 4) configure and deploy the memory plugin.
---
@@ -330,7 +343,7 @@ The helper will walk you through:
- Data storage path (defaults to absolute path, e.g. `/home/yourname/.openviking/data`)
- Volcengine Ark API Key
- VLM model name (default: `doubao-seed-2-0-pro-260215`)
- - Embedding model name (default: `doubao-embedding-vision-250615`)
+ - Embedding model name (default: `doubao-embedding-vision-251215`)
- Server ports (default: 1933 / 1833)
4. **Generate config** — creates `~/.openviking/ov.conf`
5. **Deploy plugin** — registers `memory-openviking` with OpenClaw
@@ -438,16 +451,16 @@ The plugin automatically starts and stops the OpenViking server.
},
"embedding": {
"dense": {
- "backend": "volcengine",
+ "provider": "volcengine",
"api_key": "<your-api-key>",
- "model": "doubao-embedding-vision-250615",
+ "model": "doubao-embedding-vision-251215",
"api_base": "https://ark.cn-beijing.volces.com/api/v3",
"dimension": 1024,
"input": "multimodal"
}
},
"vlm": {
- "backend": "volcengine",
+ "provider": "volcengine",
"api_key": "<your-api-key>",
"model": "doubao-seed-2-0-pro-260215",
"api_base": "https://ark.cn-beijing.volces.com/api/v3",
@@ -480,14 +493,15 @@ set OPENVIKING_GO_PATH=C:\path\to\go\bin
```
npx ./examples/openclaw-memory-plugin/setup-helper [options]
- -y, --yes Non-interactive, use defaults
- -h, --help Show help
+ -y, --yes Non-interactive, use defaults
+ --workdir <path> OpenClaw config directory (default: ~/.openclaw)
+ -h, --help Show help
Environment variables:
OPENVIKING_PYTHON Python interpreter path
OPENVIKING_CONFIG_FILE Custom ov.conf path
OPENVIKING_REPO Local repo path (auto-detected when run from repo)
- OPENVIKING_ARK_API_KEY Skip API key prompt (for CI/scripts)
+ OPENVIKING_ARK_API_KEY Volcengine API Key (skip prompt in -y mode)
```
---
diff --git a/examples/openclaw-memory-plugin/README.md b/examples/openclaw-memory-plugin/README.md
index 2a8f58bc7..363cb5706 100644
--- a/examples/openclaw-memory-plugin/README.md
+++ b/examples/openclaw-memory-plugin/README.md
@@ -10,16 +10,18 @@ npx ./examples/openclaw-memory-plugin/setup-helper
openclaw gateway
```
-The setup helper checks the environment, creates `~/.openviking/ov.conf`, deploys the plugin, and configures OpenClaw automatically.
+The setup helper checks the environment, creates `~/.openviking/ov.conf`, deploys the plugin, and configures OpenClaw automatically. It supports both **local** and **remote** modes and auto-detects multiple OpenClaw instances.
## Manual Setup
+### Local Mode
+
Prerequisites: **OpenClaw** (`npm install -g openclaw`), **Python >= 3.10** with `openviking` (`pip install openviking --upgrade --force-reinstall`).
```bash
# Install plugin
mkdir -p ~/.openclaw/extensions/memory-openviking
-cp examples/openclaw-memory-plugin/{index.ts,config.ts,openclaw.plugin.json,package.json,.gitignore} \
+cp examples/openclaw-memory-plugin/{index.ts,config.ts,client.ts,process-manager.ts,memory-ranking.ts,text-utils.ts,openclaw.plugin.json,package.json,.gitignore} \
~/.openclaw/extensions/memory-openviking/
cd ~/.openclaw/extensions/memory-openviking && npm install
@@ -33,6 +35,22 @@ openclaw config set plugins.entries.memory-openviking.config.autoRecall true --j
openclaw config set plugins.entries.memory-openviking.config.autoCapture true --json
# Start
+source ~/.openclaw/openviking.env && openclaw gateway
+```
+
+### Remote Mode
+
+Prerequisites: **OpenClaw** only. No Python/OpenViking needed.
+
+```bash
+openclaw config set plugins.enabled true
+openclaw config set plugins.slots.memory memory-openviking
+openclaw config set plugins.entries.memory-openviking.config.mode "remote"
+openclaw config set plugins.entries.memory-openviking.config.baseUrl "http://your-server:1933"
+openclaw config set plugins.entries.memory-openviking.config.apiKey "your-api-key" # optional
+openclaw config set plugins.entries.memory-openviking.config.autoRecall true --json
+openclaw config set plugins.entries.memory-openviking.config.autoCapture true --json
+
openclaw gateway
```
@@ -41,8 +59,9 @@ openclaw gateway
```
npx openclaw-openviking-setup-helper [options]
- -y, --yes Non-interactive, use defaults
- -h, --help Show help
+ -y, --yes Non-interactive, use defaults
+ --workdir <path> OpenClaw config directory (default: ~/.openclaw)
+ -h, --help Show help
Env vars:
OPENVIKING_PYTHON Python path
@@ -56,7 +75,7 @@ Env vars:
```json
{
"vlm": {
- "backend": "volcengine",
+ "provider": "volcengine",
"api_key": "<your-api-key>",
"model": "doubao-seed-2-0-pro-260215",
"api_base": "https://ark.cn-beijing.volces.com/api/v3",
@@ -65,9 +84,9 @@ Env vars:
},
"embedding": {
"dense": {
- "backend": "volcengine",
+ "provider": "volcengine",
"api_key": "<your-api-key>",
- "model": "doubao-embedding-vision-250615",
+ "model": "doubao-embedding-vision-251215",
"api_base": "https://ark.cn-beijing.volces.com/api/v3",
"dimension": 1024,
"input": "multimodal"
diff --git a/examples/openclaw-memory-plugin/client.ts b/examples/openclaw-memory-plugin/client.ts
new file mode 100644
index 000000000..9dd28bd58
--- /dev/null
+++ b/examples/openclaw-memory-plugin/client.ts
@@ -0,0 +1,262 @@
+import { createHash } from "node:crypto";
+import type { spawn } from "node:child_process";
+
+export type FindResultItem = {
+ uri: string;
+ level?: number;
+ abstract?: string;
+ overview?: string;
+ category?: string;
+ score?: number;
+ match_reason?: string;
+};
+
+export type FindResult = {
+ memories?: FindResultItem[];
+ resources?: FindResultItem[];
+ skills?: FindResultItem[];
+ total?: number;
+};
+
+export type CaptureMode = "semantic" | "keyword";
+export type ScopeName = "user" | "agent";
+export type RuntimeIdentity = {
+ userId: string;
+ agentId: string;
+};
+export type LocalClientCacheEntry = {
+ client: OpenVikingClient;
+ process: ReturnType<typeof spawn> | null;
+};
+
+export const localClientCache = new Map<string, LocalClientCacheEntry>();
+
+const MEMORY_URI_PATTERNS = [
+ /^viking:\/\/user\/(?:[^/]+\/)?memories(?:\/|$)/,
+ /^viking:\/\/agent\/(?:[^/]+\/)?memories(?:\/|$)/,
+];
+const USER_STRUCTURE_DIRS = new Set(["memories"]);
+const AGENT_STRUCTURE_DIRS = new Set(["memories", "skills", "instructions", "workspaces"]);
+
+function md5Short(input: string): string {
+ return createHash("md5").update(input).digest("hex").slice(0, 12);
+}
+
+export function isMemoryUri(uri: string): boolean {
+ return MEMORY_URI_PATTERNS.some((pattern) => pattern.test(uri));
+}
+
+export class OpenVikingClient {
+ private readonly resolvedSpaceByScope: Partial<Record<ScopeName, string>> = {};
+ private runtimeIdentity: RuntimeIdentity | null = null;
+
+ constructor(
+ private readonly baseUrl: string,
+ private readonly apiKey: string,
+ private readonly agentId: string,
+ private readonly timeoutMs: number,
+ ) {}
+
+ private async request<T>(path: string, init: RequestInit = {}): Promise<T> {
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
+ try {
+ const headers = new Headers(init.headers ?? {});
+ if (this.apiKey) {
+ headers.set("X-API-Key", this.apiKey);
+ }
+ if (this.agentId) {
+ headers.set("X-OpenViking-Agent", this.agentId);
+ }
+ if (init.body && !headers.has("Content-Type")) {
+ headers.set("Content-Type", "application/json");
+ }
+
+ const response = await fetch(`${this.baseUrl}${path}`, {
+ ...init,
+ headers,
+ signal: controller.signal,
+ });
+
+ const payload = (await response.json().catch(() => ({}))) as {
+ status?: string;
+ result?: T;
+ error?: { code?: string; message?: string };
+ };
+
+ if (!response.ok || payload.status === "error") {
+ const code = payload.error?.code ? ` [${payload.error.code}]` : "";
+ const message = payload.error?.message ?? `HTTP ${response.status}`;
+ throw new Error(`OpenViking request failed${code}: ${message}`);
+ }
+
+ return (payload.result ?? payload) as T;
+ } finally {
+ clearTimeout(timer);
+ }
+ }
+
+ async healthCheck(): Promise<void> {
+ await this.request<{ status: string }>("/health");
+ }
+
+ private async ls(uri: string): Promise<Array<Record<string, unknown>>> {
+ return this.request<Array<Record<string, unknown>>>(
+ `/api/v1/fs/ls?uri=${encodeURIComponent(uri)}&output=original`,
+ );
+ }
+
+ private async getRuntimeIdentity(): Promise<RuntimeIdentity> {
+ if (this.runtimeIdentity) {
+ return this.runtimeIdentity;
+ }
+ const fallback: RuntimeIdentity = { userId: "default", agentId: this.agentId || "default" };
+ try {
+ const status = await this.request<{ user?: unknown }>("/api/v1/system/status");
+ const userId =
+ typeof status.user === "string" && status.user.trim() ? status.user.trim() : "default";
+ this.runtimeIdentity = { userId, agentId: this.agentId || "default" };
+ return this.runtimeIdentity;
+ } catch {
+ this.runtimeIdentity = fallback;
+ return fallback;
+ }
+ }
+
+ private async resolveScopeSpace(scope: ScopeName): Promise<string> {
+ const cached = this.resolvedSpaceByScope[scope];
+ if (cached) {
+ return cached;
+ }
+
+ const identity = await this.getRuntimeIdentity();
+ const fallbackSpace =
+ scope === "user" ? identity.userId : md5Short(`${identity.userId}${identity.agentId}`);
+ const reservedDirs = scope === "user" ? USER_STRUCTURE_DIRS : AGENT_STRUCTURE_DIRS;
+ const preferredSpace =
+ scope === "user" ? identity.userId : md5Short(`${identity.userId}${identity.agentId}`);
+
+ try {
+ const entries = await this.ls(`viking://${scope}`);
+ const spaces = entries
+ .filter((entry) => entry?.isDir === true)
+ .map((entry) => (typeof entry.name === "string" ? entry.name.trim() : ""))
+ .filter((name) => name && !name.startsWith(".") && !reservedDirs.has(name));
+
+ if (spaces.length > 0) {
+ if (spaces.includes(preferredSpace)) {
+ this.resolvedSpaceByScope[scope] = preferredSpace;
+ return preferredSpace;
+ }
+ if (scope === "user" && spaces.includes("default")) {
+ this.resolvedSpaceByScope[scope] = "default";
+ return "default";
+ }
+ if (spaces.length === 1) {
+ this.resolvedSpaceByScope[scope] = spaces[0]!;
+ return spaces[0]!;
+ }
+ }
+ } catch {
+ // Fall back to identity-derived space when listing fails.
+ }
+
+ this.resolvedSpaceByScope[scope] = fallbackSpace;
+ return fallbackSpace;
+ }
+
+ private async normalizeTargetUri(targetUri: string): Promise<string> {
+ const trimmed = targetUri.trim().replace(/\/+$/, "");
+ const match = trimmed.match(/^viking:\/\/(user|agent)(?:\/(.*))?$/);
+ if (!match) {
+ return trimmed;
+ }
+ const scope = match[1] as ScopeName;
+ const rawRest = (match[2] ?? "").trim();
+ if (!rawRest) {
+ return trimmed;
+ }
+ const parts = rawRest.split("/").filter(Boolean);
+ if (parts.length === 0) {
+ return trimmed;
+ }
+
+ const reservedDirs = scope === "user" ? USER_STRUCTURE_DIRS : AGENT_STRUCTURE_DIRS;
+ if (!reservedDirs.has(parts[0]!)) {
+ return trimmed;
+ }
+
+ const space = await this.resolveScopeSpace(scope);
+ return `viking://${scope}/${space}/${parts.join("/")}`;
+ }
+
+ async find(
+ query: string,
+ options: {
+ targetUri: string;
+ limit: number;
+ scoreThreshold?: number;
+ },
+ ): Promise<FindResult> {
+ const normalizedTargetUri = await this.normalizeTargetUri(options.targetUri);
+ const body = {
+ query,
+ target_uri: normalizedTargetUri,
+ limit: options.limit,
+ score_threshold: options.scoreThreshold,
+ };
+ return this.request<FindResult>("/api/v1/search/find", {
+ method: "POST",
+ body: JSON.stringify(body),
+ });
+ }
+
+ async read(uri: string): Promise<string> {
+ return this.request<string>(
+ `/api/v1/content/read?uri=${encodeURIComponent(uri)}`,
+ );
+ }
+
+ async createSession(): Promise<string> {
+ const result = await this.request<{ session_id: string }>("/api/v1/sessions", {
+ method: "POST",
+ body: JSON.stringify({}),
+ });
+ return result.session_id;
+ }
+
+ async addSessionMessage(sessionId: string, role: string, content: string): Promise<void> {
+ await this.request<{ session_id: string }>(
+ `/api/v1/sessions/${encodeURIComponent(sessionId)}/messages`,
+ {
+ method: "POST",
+ body: JSON.stringify({ role, content }),
+ },
+ );
+ }
+
+ /** GET session so server loads messages from storage before extract (workaround for AGFS visibility). */
+ async getSession(sessionId: string): Promise<{ message_count?: number }> {
+ return this.request<{ message_count?: number }>(
+ `/api/v1/sessions/${encodeURIComponent(sessionId)}`,
+ { method: "GET" },
+ );
+ }
+
+ async extractSessionMemories(sessionId: string): Promise<Array<Record<string, unknown>>> {
+ return this.request<Array<Record<string, unknown>>>(
+ `/api/v1/sessions/${encodeURIComponent(sessionId)}/extract`,
+ { method: "POST", body: JSON.stringify({}) },
+ );
+ }
+
+ async deleteSession(sessionId: string): Promise<void> {
+ await this.request(`/api/v1/sessions/${encodeURIComponent(sessionId)}`, { method: "DELETE" });
+ }
+
+ async deleteUri(uri: string): Promise<void> {
+ await this.request(`/api/v1/fs?uri=${encodeURIComponent(uri)}&recursive=false`, {
+ method: "DELETE",
+ });
+ }
+}
diff --git a/examples/openclaw-memory-plugin/config.ts b/examples/openclaw-memory-plugin/config.ts
index e73f8645c..2be83f2aa 100644
--- a/examples/openclaw-memory-plugin/config.ts
+++ b/examples/openclaw-memory-plugin/config.ts
@@ -10,6 +10,7 @@ export type MemoryOpenVikingConfig = {
/** Port for local server when mode is "local". Ignored when mode is "remote". */
port?: number;
baseUrl?: string;
+ agentId?: string;
apiKey?: string;
targetUri?: string;
timeoutMs?: number;
@@ -30,13 +31,31 @@ const DEFAULT_TARGET_URI = "viking://user/memories";
const DEFAULT_TIMEOUT_MS = 15000;
const DEFAULT_CAPTURE_MODE = "semantic";
const DEFAULT_CAPTURE_MAX_LENGTH = 24000;
-const DEFAULT_RECALL_LIMIT = 6;
+const DEFAULT_RECALL_LIMIT = 20;
const DEFAULT_RECALL_SCORE_THRESHOLD = 0.01;
const DEFAULT_INGEST_REPLY_ASSIST = true;
const DEFAULT_INGEST_REPLY_ASSIST_MIN_SPEAKER_TURNS = 2;
const DEFAULT_INGEST_REPLY_ASSIST_MIN_CHARS = 120;
const DEFAULT_LOCAL_CONFIG_PATH = join(homedir(), ".openviking", "ov.conf");
+function generateAgentId(): string {
+ const { hostname } = require("node:os") as typeof import("node:os");
+ const { randomBytes } = require("node:crypto") as typeof import("node:crypto");
+ const host = hostname().split(".")[0]?.toLowerCase().replace(/[^a-z0-9-]/g, "") || "local";
+ const random = randomBytes(4).toString("hex");
+ return `openclaw-${host}-${random}`;
+}
+
+function resolveAgentId(configured: unknown): string {
+ if (typeof configured === "string" && configured.trim()) {
+ return configured.trim();
+ }
+ // 生成随机唯一的默认 ID,不持久化
+ return generateAgentId();
+}
+
+export { generateAgentId };
+
function resolveEnvVars(value: string): string {
return value.replace(/\$\{([^}]+)\}/g, (_, envVar) => {
const envValue = process.env[envVar];
@@ -89,6 +108,7 @@ export const memoryOpenVikingConfigSchema = {
"configPath",
"port",
"baseUrl",
+ "agentId",
"apiKey",
"targetUri",
"timeoutMs",
@@ -136,6 +156,7 @@ export const memoryOpenVikingConfigSchema = {
configPath,
port,
baseUrl: resolvedBaseUrl,
+ agentId: resolveAgentId(cfg.agentId),
apiKey: rawApiKey ? resolveEnvVars(rawApiKey) : "",
targetUri: typeof cfg.targetUri === "string" ? cfg.targetUri : DEFAULT_TARGET_URI,
timeoutMs: Math.max(1000, Math.floor(toNumber(cfg.timeoutMs, DEFAULT_TIMEOUT_MS))),
@@ -194,6 +215,11 @@ export const memoryOpenVikingConfigSchema = {
placeholder: DEFAULT_BASE_URL,
help: "HTTP URL when mode is remote (or use ${OPENVIKING_BASE_URL})",
},
+ agentId: {
+ label: "Agent ID",
+ placeholder: "auto-generated",
+ help: "Identifies this agent to OpenViking (sent as X-OpenViking-Agent header). A random unique ID is generated per session if not set.",
+ },
apiKey: {
label: "OpenViking API Key",
sensitive: true,
diff --git a/examples/openclaw-memory-plugin/demo-memory-ajie.py b/examples/openclaw-memory-plugin/demo-memory-ajie.py
new file mode 100644
index 000000000..76fa6e605
--- /dev/null
+++ b/examples/openclaw-memory-plugin/demo-memory-ajie.py
@@ -0,0 +1,233 @@
+#!/usr/bin/env python3
+"""
+OpenClaw Memory Plugin 演示脚本 — 用户: 阿杰(后端开发)
+
+通过 OpenClaw Gateway 的 Responses API (/v1/responses) 进行多轮对话,
+验证 OpenViking 记忆插件的端到端能力。消息经过完整 agent 流水线,
+插件的 before_agent_start(记忆注入)和 agent_end(记忆抽取)自动触发。
+
+前提: OpenClaw 配置中需开启 Responses API。在 openclaw.config.json 的 gateways 中添加:
+
+ {
+ "type": "openresponses-http",
+ "port": 18789
+ }
+
+然后启动 OpenClaw 即可在该端口使用 /v1/responses 端点。
+
+用法:
+ python demo-memory-ajie.py
+ python demo-memory-ajie.py --gateway http://127.0.0.1:18789
+ python demo-memory-ajie.py --phase chat # 只跑对话
+ python demo-memory-ajie.py --phase verify # 只跑验证(需先跑 chat)
+
+依赖:
+ pip install requests rich
+"""
+
+import argparse
+import sys
+import time
+
+import requests
+from rich.console import Console
+from rich.markdown import Markdown
+from rich.panel import Panel
+from rich.table import Table
+
+# ── 常量 ───────────────────────────────────────────────────────────────────
+
+USER_ID = "ajie"
+DISPLAY_NAME = "阿杰"
+DEFAULT_GATEWAY = "http://127.0.0.1:18789"
+
+console = Console()
+
+# ── 对话数据 (10 轮) ──────────────────────────────────────────────────────
+
+CHAT_MESSAGES = [
+ # 第1轮 — 开场介绍
+ "嗨,我是阿杰,是个后端开发工程师,最近在优化我们系统的性能。想找个助手帮我记录一下平时遇到的技术问题和解决方案,你能帮帮我吗?",
+ # 第2轮 — Redis 缓存问题
+ "说到问题,前几天刚遇到一个 Redis 缓存击穿的情况。热门商品的缓存过期了,瞬间大量请求打到数据库,差点把 DB 搞挂了。后来我加了互斥锁,只有一个请求去查 DB 并刷新缓存,才解决了问题。",
+ # 第3轮 — MySQL 慢查询
+ "还有个 MySQL 的问题,之前有个订单列表查询特别慢,看了一下慢查询日志,发现是没加索引。给 create_time 和 user_id 加了联合索引之后,查询时间从 2 秒降到了 50 毫秒,效果特别明显。",
+ # 第4轮 — Kafka 削峰填谷
+ "对了,我们还用 Kafka 做了削峰填谷。订单创建成功后先写入 Kafka,然后消费者慢慢处理,这样即使是秒杀活动也不怕了。我们还在 Kafka 里做了订单超时检查,30 分钟未支付的订单自动取消。",
+ # 第5轮 — 技术栈介绍
+ "说一下我们的技术栈吧:后端用的是 Spring Boot,缓存用 Redis,数据库是 MySQL,消息队列是 Kafka。部署在 Kubernetes 上,用 Prometheus + Grafana 做监控。你对这套技术栈熟悉吗?",
+ # 第6轮 — 工作习惯
+ "我一般早上 9 点到公司,先花 15 分钟看一下监控面板和告警信息,确保系统正常运行。然后上午写代码,下午开会或者帮同事 review code。对了,我用 IntelliJ IDEA 写代码,快捷键超好用!",
+ # 第7轮 — 踩过的坑
+ "说起踩过的坑,那可多了!比如有一次把 Redis 的过期时间设成了 10 秒而不是 10 分钟,结果缓存频繁失效;还有一次 MySQL 连接池满了,是因为有个地方连接没释放。每次踩坑我都会记下来,避免再犯。",
+ # 第8轮 — 最近在学习
+ "最近在看《Redis 设计与实现》这本书,讲得真好,终于理解 Redis 的数据结构底层是怎么实现的了。之前还看过《高性能 MySQL》,收获也很大。你有什么技术书推荐吗?",
+ # 第9轮 — 今天的任务
+ "今天的任务:晚上要优化一下 Kafka 消费者的配置,现在消费速度有点慢,想把批量消费参数调大一点。还有,要帮新来的同事小林搭建一下开发环境,他对 Kafka 不太熟。",
+ # 第10轮 — 对话偏好
+ "好的,以后跟我聊技术问题的时候,先讲一下原理,再给具体的代码示例,这样我理解得更透彻。另外,多提一些最佳实践,我想写出更健壮的代码。谢谢啦!",
+]
+
+# ── 验证数据 (5 轮) ──────────────────────────────────────────────────────
+
+VERIFY_QUESTIONS = [
+ {"question": "帮我回忆一下最近遇到的技术问题和解决方案,请简洁回答", "expected": "Redis 缓存击穿加互斥锁、MySQL 加索引、Kafka 削峰填谷"},
+ {"question": "我们的技术栈是什么?请简洁回答", "expected": "Spring Boot、Redis、MySQL、Kafka、K8s、Prometheus + Grafana"},
+ {"question": "我踩过哪些技术坑?请简洁回答", "expected": "Redis 过期时间设错、MySQL 连接池满了"},
+ {"question": "我的工作习惯是怎样的?请简洁回答", "expected": "早上看监控、上午写代码、下午开会/review,用 IDEA"},
+ {"question": "最近在看什么技术书?请简洁回答", "expected": "Redis 设计与实现、高性能 MySQL"},
+]
+
+
+# ── 辅助函数 ───────────────────────────────────────────────────────────────
+
+
+def send_message(gateway_url, message, user_id, previous_messages=None):
+ """通过 OpenClaw Responses API 发送消息。"""
+ # OpenClaw Responses API 只接受单条消息作为输入,不接受历史消息数组
+ input_data = message
+ resp = requests.post(
+ f"{gateway_url}/v1/responses",
+ json={"model": "openclaw", "input": input_data, "user": user_id},
+ timeout=300,
+ )
+ resp.raise_for_status()
+ return resp.json()
+
+
+def extract_reply_text(data):
+ """从 Responses API 响应中提取助手回复文本。"""
+ for item in data.get("output", []):
+ if item.get("type") == "message" and item.get("role") == "assistant":
+ for part in item.get("content", []):
+ if part.get("type") in ("text", "output_text"):
+ return part.get("text", "")
+ return "(无回复)"
+
+
+def render_reply(text):
+ """用 rich 渲染助手回复。"""
+ lines = text.split("\n")
+ if len(lines) > 30:
+ text = "\n".join(lines[:30]) + f"\n\n... (共 {len(lines)} 行,已截断)"
+ console.print(Panel(Markdown(text), title="[green]回复[/green]", border_style="green"))
+
+
+# ── 主流程 ─────────────────────────────────────────────────────────────────
+
+
+def run_chat(gateway_url, delay):
+ console.print()
+ console.rule(f"[bold]Phase 1: 多轮对话 — {DISPLAY_NAME} ({len(CHAT_MESSAGES)} 轮)[/bold]")
+ console.print(f"[yellow]用户:[/yellow] {DISPLAY_NAME} (user={USER_ID})")
+ console.print(f"[yellow]Gateway:[/yellow] {gateway_url}")
+ console.print(f"[yellow]轮次间隔:[/yellow] {delay}s")
+
+ total = len(CHAT_MESSAGES)
+ ok = fail = 0
+ messages = [] # 维护对话历史
+
+ for i, msg in enumerate(CHAT_MESSAGES, 1):
+ console.rule(f"[dim]{i}/{total}[/dim]", style="dim")
+ console.print(Panel(msg, title=f"[bold cyan]用户 [{i}/{total}][/bold cyan]", border_style="cyan"))
+ try:
+ data = send_message(gateway_url, msg, USER_ID, messages if messages else None)
+ reply = extract_reply_text(data)
+ messages.append({"role": "user", "content": msg})
+ messages.append({"role": "assistant", "content": reply})
+ render_reply(reply)
+ ok += 1
+ except Exception as e:
+ console.print(f"[red][ERROR][/red] {e}")
+ fail += 1
+ if i < total:
+ time.sleep(delay)
+
+ console.print()
+ console.print(f"[yellow]对话完成:[/yellow] {ok} 成功, {fail} 失败")
+
+ wait = max(delay * 2, 5)
+ console.print(f"[yellow]等待 {wait:.0f}s 让记忆抽取完成...[/yellow]")
+ time.sleep(wait)
+
+
+def run_verify(gateway_url, delay):
+ console.print()
+ console.rule(f"[bold]Phase 2: 验证记忆召回 — {DISPLAY_NAME} 新 Session ({len(VERIFY_QUESTIONS)} 轮)[/bold]")
+
+ # 用不同的 user 后缀确保 Gateway 派生出新 session
+ verify_user = f"{USER_ID}-verify"
+ console.print(f"[yellow]验证用户:[/yellow] {verify_user} (新 session,不带对话历史)")
+
+ results = []
+ total = len(VERIFY_QUESTIONS)
+
+ for i, item in enumerate(VERIFY_QUESTIONS, 1):
+ q, expected = item["question"], item["expected"]
+ console.rule(f"[dim]{i}/{total}[/dim]", style="dim")
+ console.print(Panel(
+ f"{q}\n[dim]期望召回: {expected}[/dim]",
+ title=f"[bold cyan]验证 [{i}/{total}][/bold cyan]",
+ border_style="cyan",
+ ))
+
+ try:
+ # 每题独立发送,不带历史 → 回答正确 = 记忆召回生效
+ data = send_message(gateway_url, q, verify_user)
+ reply = extract_reply_text(data)
+ render_reply(reply)
+ results.append({"expected": expected, "success": True})
+ except Exception as e:
+ console.print(f"[red][ERROR][/red] {e}")
+ results.append({"expected": expected, "success": False})
+
+ if i < total:
+ time.sleep(delay)
+
+ # 汇总表格
+ console.print()
+ console.rule(f"[bold]结果汇总 — {DISPLAY_NAME}[/bold]")
+
+ table = Table(title=f"记忆召回验证 — {DISPLAY_NAME} ({USER_ID})")
+ table.add_column("#", style="bold", width=4)
+ table.add_column("状态", width=6)
+ table.add_column("期望召回", style="dim")
+
+ for i, r in enumerate(results, 1):
+ status = "[green]OK[/green]" if r.get("success") else "[red]FAIL[/red]"
+ table.add_row(str(i), status, r["expected"])
+
+ console.print(table)
+
+ ok = sum(1 for r in results if r.get("success"))
+ console.print(f"\n[yellow]成功: {ok}/{total}[/yellow]")
+ console.print("[yellow]验证方式: 每个问题在新 session 中独立发送(无对话历史),回答正确说明 before_agent_start hook 成功召回了记忆。[/yellow]")
+
+
+# ── 入口 ───────────────────────────────────────────────────────────────────
+
+
+def main():
+ parser = argparse.ArgumentParser(description=f"Memory 演示 — {DISPLAY_NAME}")
+ parser.add_argument("--gateway", default=DEFAULT_GATEWAY,
+ help=f"OpenClaw Gateway 地址 (默认: {DEFAULT_GATEWAY})")
+ parser.add_argument("--phase", choices=["all", "chat", "verify"], default="all",
+ help="all=全部, chat=仅对话, verify=仅验证 (默认: all)")
+ parser.add_argument("--delay", type=float, default=3.0,
+ help="轮次间等待秒数 (默认: 3)")
+ args = parser.parse_args()
+
+ gateway_url = args.gateway.rstrip("/")
+ console.print(f"[bold]OpenClaw Memory Plugin 演示 — {DISPLAY_NAME}[/bold]")
+ console.print(f"[yellow]Gateway:[/yellow] {gateway_url}")
+
+ if args.phase in ("all", "chat"):
+ run_chat(gateway_url, args.delay)
+ if args.phase in ("all", "verify"):
+ run_verify(gateway_url, args.delay)
+
+ console.print("\n[yellow]演示完成。[/yellow]")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/openclaw-memory-plugin/demo-memory-xiaomei.py b/examples/openclaw-memory-plugin/demo-memory-xiaomei.py
new file mode 100644
index 000000000..8d2584436
--- /dev/null
+++ b/examples/openclaw-memory-plugin/demo-memory-xiaomei.py
@@ -0,0 +1,233 @@
+#!/usr/bin/env python3
+"""
+OpenClaw Memory Plugin 演示脚本 — 用户: 小美(日常生活记录)
+
+通过 OpenClaw Gateway 的 Responses API (/v1/responses) 进行多轮对话,
+验证 OpenViking 记忆插件的端到端能力。消息经过完整 agent 流水线,
+插件的 before_agent_start(记忆注入)和 agent_end(记忆抽取)自动触发。
+
+前提: OpenClaw 配置中需开启 Responses API。在 openclaw.config.json 的 gateways 中添加:
+
+ {
+ "type": "openresponses-http",
+ "port": 18790
+ }
+
+然后启动 OpenClaw 即可在该端口使用 /v1/responses 端点。
+
+用法:
+ python demo-memory-xiaomei.py
+ python demo-memory-xiaomei.py --gateway http://127.0.0.1:2026
+ python demo-memory-xiaomei.py --phase chat # 只跑对话
+ python demo-memory-xiaomei.py --phase verify # 只跑验证(需先跑 chat)
+
+依赖:
+ pip install requests rich
+"""
+
+import argparse
+import sys
+import time
+
+import requests
+from rich.console import Console
+from rich.markdown import Markdown
+from rich.panel import Panel
+from rich.table import Table
+
+# ── 常量 ───────────────────────────────────────────────────────────────────
+
+USER_ID = "xiaomei"
+DISPLAY_NAME = "小美"
+DEFAULT_GATEWAY = "http://127.0.0.1:18790"
+
+console = Console()
+
+# ── 对话数据 (10 轮) ──────────────────────────────────────────────────────
+
+CHAT_MESSAGES = [
+ # 第1轮 — 开场介绍
+ "嗨!我是小美,刚毕业不久,现在在一家互联网公司做运营。我想找个能帮我记录日常生活的小助手,比如记一下每天发生的事情、我的想法、还有想做的事情。你能帮帮我吗?",
+ # 第2轮 — 今天的心情和工作
+ "今天心情还不错!早上在地铁上看到了一个超级可爱的小猫咪,它主人带着它坐车,只露出个小脑袋,太萌了!对了,今天部门开会说下个月要做 618 大促,我负责写活动文案,有点紧张,这是我第一次独立负责这么重要的项目。",
+ # 第3轮 — 饮食习惯
+ "说到吃,中午我跟同事小丽一起去吃了楼下那家麻辣烫,超级好吃!我喜欢多放醋和麻酱,不太能吃辣。不过最近在减肥,不敢吃太多主食。你有没有什么好吃又不胖的推荐呀?",
+ # 第4轮 — 运动计划
+ "对了,我办了一张健身卡,就在我家小区旁边。上周去了一次,跑了 30 分钟步,还练了会儿瑜伽。结果第二天腿酸得不行,下楼都费劲。教练说让我每周去三次,我怕坚持不下来...",
+ # 第5轮 — 周末的计划
+ "这个周末你有什么建议吗?我想跟我男朋友一起出去。我们之前想过去看樱花,但好像花期快过了。要不看电影?最近有什么好看的电影吗?或者去探店?我知道有一家咖啡馆好像很不错。",
+ # 第6轮 — 我的爱好
+ "说起来,我平时喜欢追剧,尤其是那种甜宠剧,最近在看《归路》,太甜了!我还喜欢画画,虽然画得不太好,但挺解压的。偶尔也会看看书,最近在看《被讨厌的勇气》,挺有启发的。",
+ # 第7轮 — 过敏和小习惯
+ "哎呀,我差点忘了提醒你!我对芒果过敏,吃了会起疹子。上次在公司同事给了我一个芒果蛋糕,我不知道,吃了一口就进医院了,还好不严重。还有,我每天晚上睡觉前都要喝一杯热牛奶,不然会失眠。",
+ # 第8轮 — 想买的东西
+ "最近我种草了一个拍立得,就是富士的 mini12,粉色那款,颜值超级高!但有点贵,要 700 多块钱,还在犹豫要不要买。对了,我还想买一个投影仪,这样周末可以在家看电影。",
+ # 第9轮 — 同事和朋友
+ "说到同事,小丽人超好,她说会帮我一起想 618 的文案点子。还有,我闺蜜下周要结婚了!她是我们宿舍第一个结婚的,真为她开心。我还在想送什么礼物好呢,红包肯定要包,但想再加点特别的。",
+ # 第10轮 — 对话风格偏好
+ "好的,谢谢你听我说了这么多!以后跟我聊天的时候,轻松一点就好,像朋友一样。如果我不开心了,多安慰安慰我;如果我开心,就跟我一起开心。对了,多给我推荐好吃的好玩的,谢谢啦!",
+]
+
+# ── 验证数据 (5 轮) ──────────────────────────────────────────────────────
+
+VERIFY_QUESTIONS = [
+ {"question": "帮我回忆一下我最近的生活和工作情况,请简洁回答", "expected": "618 活动文案、同事小丽、健身计划、减肥中"},
+ {"question": "周末想跟男朋友出去,有什么建议吗?请简洁回答", "expected": "樱花花期快过了,看电影或探店,喜欢咖啡馆"},
+ {"question": "想吃点东西,有什么要注意的吗?请简洁回答", "expected": "对芒果过敏,喜欢麻辣烫多放醋和麻酱,减肥中少吃主食"},
+ {"question": "我平时有什么爱好?请简洁回答", "expected": "追甜宠剧、画画、看书(被讨厌的勇气)"},
+ {"question": "我最近想买什么东西?请简洁回答", "expected": "富士 mini12 粉色拍立得、投影仪"},
+]
+
+
+# ── 辅助函数 ───────────────────────────────────────────────────────────────
+
+
+def send_message(gateway_url, message, user_id, previous_messages=None):
+ """通过 OpenClaw Responses API 发送消息。"""
+ # OpenClaw Responses API 只接受单条消息作为输入,不接受历史消息数组
+ input_data = message
+ resp = requests.post(
+ f"{gateway_url}/v1/responses",
+ json={"model": "openclaw", "input": input_data, "user": user_id},
+ timeout=300,
+ )
+ resp.raise_for_status()
+ return resp.json()
+
+
+def extract_reply_text(data):
+ """从 Responses API 响应中提取助手回复文本。"""
+ for item in data.get("output", []):
+ if item.get("type") == "message" and item.get("role") == "assistant":
+ for part in item.get("content", []):
+ if part.get("type") in ("text", "output_text"):
+ return part.get("text", "")
+ return "(无回复)"
+
+
+def render_reply(text):
+ """用 rich 渲染助手回复。"""
+ lines = text.split("\n")
+ if len(lines) > 30:
+ text = "\n".join(lines[:30]) + f"\n\n... (共 {len(lines)} 行,已截断)"
+ console.print(Panel(Markdown(text), title="[green]回复[/green]", border_style="green"))
+
+
+# ── 主流程 ─────────────────────────────────────────────────────────────────
+
+
+def run_chat(gateway_url, delay):
+ console.print()
+ console.rule(f"[bold]Phase 1: 多轮对话 — {DISPLAY_NAME} ({len(CHAT_MESSAGES)} 轮)[/bold]")
+ console.print(f"[yellow]用户:[/yellow] {DISPLAY_NAME} (user={USER_ID})")
+ console.print(f"[yellow]Gateway:[/yellow] {gateway_url}")
+ console.print(f"[yellow]轮次间隔:[/yellow] {delay}s")
+
+ total = len(CHAT_MESSAGES)
+ ok = fail = 0
+ messages = [] # 维护对话历史
+
+ for i, msg in enumerate(CHAT_MESSAGES, 1):
+ console.rule(f"[dim]{i}/{total}[/dim]", style="dim")
+ console.print(Panel(msg, title=f"[bold cyan]用户 [{i}/{total}][/bold cyan]", border_style="cyan"))
+ try:
+ data = send_message(gateway_url, msg, USER_ID, messages if messages else None)
+ reply = extract_reply_text(data)
+ messages.append({"role": "user", "content": msg})
+ messages.append({"role": "assistant", "content": reply})
+ render_reply(reply)
+ ok += 1
+ except Exception as e:
+ console.print(f"[red][ERROR][/red] {e}")
+ fail += 1
+ if i < total:
+ time.sleep(delay)
+
+ console.print()
+ console.print(f"[yellow]对话完成:[/yellow] {ok} 成功, {fail} 失败")
+
+ wait = max(delay * 2, 5)
+ console.print(f"[yellow]等待 {wait:.0f}s 让记忆抽取完成...[/yellow]")
+ time.sleep(wait)
+
+
+def run_verify(gateway_url, delay):
+ console.print()
+ console.rule(f"[bold]Phase 2: 验证记忆召回 — {DISPLAY_NAME} 新 Session ({len(VERIFY_QUESTIONS)} 轮)[/bold]")
+
+ # 用不同的 user 后缀确保 Gateway 派生出新 session
+ verify_user = f"{USER_ID}-verify"
+ console.print(f"[yellow]验证用户:[/yellow] {verify_user} (新 session,不带对话历史)")
+
+ results = []
+ total = len(VERIFY_QUESTIONS)
+
+ for i, item in enumerate(VERIFY_QUESTIONS, 1):
+ q, expected = item["question"], item["expected"]
+ console.rule(f"[dim]{i}/{total}[/dim]", style="dim")
+ console.print(Panel(
+ f"{q}\n[dim]期望召回: {expected}[/dim]",
+ title=f"[bold cyan]验证 [{i}/{total}][/bold cyan]",
+ border_style="cyan",
+ ))
+
+ try:
+ # 每题独立发送,不带历史 → 回答正确 = 记忆召回生效
+ data = send_message(gateway_url, q, verify_user)
+ reply = extract_reply_text(data)
+ render_reply(reply)
+ results.append({"expected": expected, "success": True})
+ except Exception as e:
+ console.print(f"[red][ERROR][/red] {e}")
+ results.append({"expected": expected, "success": False})
+
+ if i < total:
+ time.sleep(delay)
+
+ # 汇总表格
+ console.print()
+ console.rule(f"[bold]结果汇总 — {DISPLAY_NAME}[/bold]")
+
+ table = Table(title=f"记忆召回验证 — {DISPLAY_NAME} ({USER_ID})")
+ table.add_column("#", style="bold", width=4)
+ table.add_column("状态", width=6)
+ table.add_column("期望召回", style="dim")
+
+ for i, r in enumerate(results, 1):
+ status = "[green]OK[/green]" if r.get("success") else "[red]FAIL[/red]"
+ table.add_row(str(i), status, r["expected"])
+
+ console.print(table)
+
+ ok = sum(1 for r in results if r.get("success"))
+ console.print(f"\n[yellow]成功: {ok}/{total}[/yellow]")
+ console.print("[yellow]验证方式: 每个问题在新 session 中独立发送(无对话历史),回答正确说明 before_agent_start hook 成功召回了记忆。[/yellow]")
+
+
+# ── 入口 ───────────────────────────────────────────────────────────────────
+
+
+def main():
+ parser = argparse.ArgumentParser(description=f"Memory 演示 — {DISPLAY_NAME}")
+ parser.add_argument("--gateway", default=DEFAULT_GATEWAY,
+ help=f"OpenClaw Gateway 地址 (默认: {DEFAULT_GATEWAY})")
+ parser.add_argument("--phase", choices=["all", "chat", "verify"], default="all",
+ help="all=全部, chat=仅对话, verify=仅验证 (默认: all)")
+ parser.add_argument("--delay", type=float, default=3.0,
+ help="轮次间等待秒数 (默认: 3)")
+ args = parser.parse_args()
+
+ gateway_url = args.gateway.rstrip("/")
+ console.print(f"[bold]OpenClaw Memory Plugin 演示 — {DISPLAY_NAME}[/bold]")
+ console.print(f"[yellow]Gateway:[/yellow] {gateway_url}")
+
+ if args.phase in ("all", "chat"):
+ run_chat(gateway_url, args.delay)
+ if args.phase in ("all", "verify"):
+ run_verify(gateway_url, args.delay)
+
+ console.print("\n[yellow]演示完成。[/yellow]")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/openclaw-memory-plugin/index.ts b/examples/openclaw-memory-plugin/index.ts
index 6aae9e558..19eaab1f3 100644
--- a/examples/openclaw-memory-plugin/index.ts
+++ b/examples/openclaw-memory-plugin/index.ts
@@ -1,990 +1,37 @@
-import { spawn, execSync } from "node:child_process";
-import { createHash } from "node:crypto";
-import { readFileSync, existsSync } from "node:fs";
-import { Socket } from "node:net";
-import { join } from "node:path";
-import { homedir, tmpdir, platform } from "node:os";
+import { spawn } from "node:child_process";
+import { tmpdir } from "node:os";
-const IS_WIN = platform() === "win32";
import type { OpenClawPluginApi } from "openclaw/plugin-sdk";
import { Type } from "@sinclair/typebox";
import { memoryOpenVikingConfigSchema } from "./config.js";
-type FindResultItem = {
- uri: string;
- is_leaf?: boolean;
- abstract?: string;
- overview?: string;
- category?: string;
- score?: number;
- match_reason?: string;
-};
-
-type FindResult = {
- memories?: FindResultItem[];
- resources?: FindResultItem[];
- skills?: FindResultItem[];
- total?: number;
-};
-
-type CaptureMode = "semantic" | "keyword";
-type ScopeName = "user" | "agent";
-type RuntimeIdentity = {
- userId: string;
- agentId: string;
-};
-type LocalClientCacheEntry = {
- client: OpenVikingClient;
- process: ReturnType<typeof spawn> | null;
-};
-
-const localClientCache = new Map<string, LocalClientCacheEntry>();
-
-const MEMORY_URI_PATTERNS = [
- /^viking:\/\/user\/(?:[^/]+\/)?memories(?:\/|$)/,
- /^viking:\/\/agent\/(?:[^/]+\/)?memories(?:\/|$)/,
-];
-const USER_STRUCTURE_DIRS = new Set(["memories"]);
-const AGENT_STRUCTURE_DIRS = new Set(["memories", "skills", "instructions", "workspaces"]);
-
-function md5Short(input: string): string {
- return createHash("md5").update(input).digest("hex").slice(0, 12);
-}
-
-const MEMORY_TRIGGERS = [
- /remember|preference|prefer|important|decision|decided|always|never/i,
- /记住|偏好|喜欢|喜爱|崇拜|讨厌|害怕|重要|决定|总是|永远|优先|习惯|爱好|擅长|最爱|不喜欢/i,
- /[\w.-]+@[\w.-]+\.\w+/,
- /\+\d{10,}/,
- /(?:我|my)\s*(?:是|叫|名字|name|住在|live|来自|from|生日|birthday|电话|phone|邮箱|email)/i,
- /(?:我|i)\s*(?:喜欢|崇拜|讨厌|害怕|擅长|不会|爱|恨|想要|需要|希望|觉得|认为|相信)/i,
- /(?:favorite|favourite|love|hate|enjoy|dislike|admire|idol|fan of)/i,
-];
-
-const CJK_CHAR_REGEX = /[\u3040-\u30ff\u3400-\u9fff\uf900-\ufaff\uac00-\ud7af]/;
-const RELEVANT_MEMORIES_BLOCK_RE = /<relevant-memories>[\s\S]*?<\/relevant-memories>/gi;
-const CONVERSATION_METADATA_BLOCK_RE =
- /(?:^|\n)\s*(?:Conversation info|Conversation metadata|会话信息|对话信息)\s*(?:\([^)]+\))?\s*:\s*```[\s\S]*?```/gi;
-/** Strips "Sender (untrusted metadata): ```json ... ```" so capture sends clean text to OpenViking extract. */
-const SENDER_METADATA_BLOCK_RE = /Sender\s*\([^)]*\)\s*:\s*```[\s\S]*?```/gi;
-const FENCED_JSON_BLOCK_RE = /```json\s*([\s\S]*?)```/gi;
-const METADATA_JSON_KEY_RE =
- /"(session|sessionid|sessionkey|conversationid|channel|sender|userid|agentid|timestamp|timezone)"\s*:/gi;
-const LEADING_TIMESTAMP_PREFIX_RE = /^\s*\[[^\]\n]{1,120}\]\s*/;
-const COMMAND_TEXT_RE = /^\/[a-z0-9_-]{1,64}\b/i;
-const NON_CONTENT_TEXT_RE = /^[\p{P}\p{S}\s]+$/u;
-const SUBAGENT_CONTEXT_RE = /^\s*\[Subagent Context\]/i;
-const MEMORY_INTENT_RE = /记住|记下|remember|save|store|偏好|preference|规则|rule|事实|fact/i;
-const QUESTION_CUE_RE =
- /[??]|\b(?:what|when|where|who|why|how|which|can|could|would|did|does|is|are)\b|^(?:请问|能否|可否|怎么|如何|什么时候|谁|什么|哪|是否)/i;
-const CAPTURE_LIMIT = 3;
-const SPEAKER_TAG_RE = /(?:^|\s)([A-Za-z\u4e00-\u9fa5][A-Za-z0-9_\u4e00-\u9fa5-]{1,30}):\s/g;
-const DEFAULT_AGFS_PORT = 1833;
-
-/** Read AGFS port from OpenViking config (ov.conf). Used so we can clean both OpenViking and AGFS ports. */
-function getAgfsPortFromConfig(configPath: string): number {
- try {
- if (!existsSync(configPath)) return DEFAULT_AGFS_PORT;
- const raw = readFileSync(configPath, "utf-8");
- const obj = JSON.parse(raw) as { storage?: { agfs?: { port?: number } } };
- const p = obj?.storage?.agfs?.port;
- return typeof p === "number" && p >= 1 && p <= 65535 ? p : DEFAULT_AGFS_PORT;
- } catch {
- return DEFAULT_AGFS_PORT;
- }
-}
-
-function resolveCaptureMinLength(text: string): number {
- return CJK_CHAR_REGEX.test(text) ? 4 : 10;
-}
-
-function looksLikeMetadataJsonBlock(content: string): boolean {
- const matchedKeys = new Set<string>();
- const matches = content.matchAll(METADATA_JSON_KEY_RE);
- for (const match of matches) {
- const key = (match[1] ?? "").toLowerCase();
- if (key) {
- matchedKeys.add(key);
- }
- }
- return matchedKeys.size >= 3;
-}
-
-function sanitizeUserTextForCapture(text: string): string {
- return text
- .replace(RELEVANT_MEMORIES_BLOCK_RE, " ")
- .replace(CONVERSATION_METADATA_BLOCK_RE, " ")
- .replace(SENDER_METADATA_BLOCK_RE, " ")
- .replace(FENCED_JSON_BLOCK_RE, (full, inner) =>
- looksLikeMetadataJsonBlock(String(inner ?? "")) ? " " : full,
- )
- .replace(LEADING_TIMESTAMP_PREFIX_RE, "")
- .replace(/^\s*\[[^\]\n]{1,120}\]\s*/, "")
- .replace(/\u0000/g, "")
- .replace(/\s+/g, " ")
- .trim();
-}
-
-function looksLikeQuestionOnlyText(text: string): boolean {
- if (!QUESTION_CUE_RE.test(text) || MEMORY_INTENT_RE.test(text)) {
- return false;
- }
- // Multi-speaker transcripts often contain many "?" but should still be captured.
- const speakerTags = text.match(/[A-Za-z\u4e00-\u9fa5]{2,20}:\s/g) ?? [];
- if (speakerTags.length >= 2 || text.length > 280) {
- return false;
- }
- return true;
-}
-
-type TranscriptLikeIngestDecision = {
- shouldAssist: boolean;
- reason: string;
- normalizedText: string;
- speakerTurns: number;
- chars: number;
-};
-
-function countSpeakerTurns(text: string): number {
- let count = 0;
- for (const _match of text.matchAll(SPEAKER_TAG_RE)) {
- count += 1;
- }
- return count;
-}
-
-function isTranscriptLikeIngest(
- text: string,
- options: {
- minSpeakerTurns: number;
- minChars: number;
- },
-): TranscriptLikeIngestDecision {
- const normalizedText = sanitizeUserTextForCapture(text.trim());
- if (!normalizedText) {
- return {
- shouldAssist: false,
- reason: "empty_text",
- normalizedText,
- speakerTurns: 0,
- chars: 0,
- };
- }
-
- if (COMMAND_TEXT_RE.test(normalizedText)) {
- return {
- shouldAssist: false,
- reason: "command_text",
- normalizedText,
- speakerTurns: 0,
- chars: normalizedText.length,
- };
- }
-
- if (SUBAGENT_CONTEXT_RE.test(normalizedText)) {
- return {
- shouldAssist: false,
- reason: "subagent_context",
- normalizedText,
- speakerTurns: 0,
- chars: normalizedText.length,
- };
- }
-
- if (NON_CONTENT_TEXT_RE.test(normalizedText)) {
- return {
- shouldAssist: false,
- reason: "non_content_text",
- normalizedText,
- speakerTurns: 0,
- chars: normalizedText.length,
- };
- }
-
- if (looksLikeQuestionOnlyText(normalizedText)) {
- return {
- shouldAssist: false,
- reason: "question_text",
- normalizedText,
- speakerTurns: 0,
- chars: normalizedText.length,
- };
- }
-
- const chars = normalizedText.length;
- if (chars < options.minChars) {
- return {
- shouldAssist: false,
- reason: "chars_below_threshold",
- normalizedText,
- speakerTurns: 0,
- chars,
- };
- }
-
- const speakerTurns = countSpeakerTurns(normalizedText);
- if (speakerTurns < options.minSpeakerTurns) {
- return {
- shouldAssist: false,
- reason: "speaker_turns_below_threshold",
- normalizedText,
- speakerTurns,
- chars,
- };
- }
-
- return {
- shouldAssist: true,
- reason: "transcript_like_ingest",
- normalizedText,
- speakerTurns,
- chars,
- };
-}
-
-function normalizeCaptureDedupeText(text: string): string {
- return normalizeDedupeText(text).replace(/[\p{P}\p{S}]+/gu, " ").replace(/\s+/g, " ").trim();
-}
-
-function pickRecentUniqueTexts(texts: string[], limit: number): string[] {
- if (limit <= 0 || texts.length === 0) {
- return [];
- }
- const seen = new Set<string>();
- const picked: string[] = [];
- for (let i = texts.length - 1; i >= 0; i -= 1) {
- const text = texts[i];
- const key = normalizeCaptureDedupeText(text);
- if (!key || seen.has(key)) {
- continue;
- }
- seen.add(key);
- picked.push(text);
- if (picked.length >= limit) {
- break;
- }
- }
- return picked.reverse();
-}
-
-function getCaptureDecision(text: string, mode: CaptureMode, captureMaxLength: number): {
- shouldCapture: boolean;
- reason: string;
- normalizedText: string;
-} {
- const trimmed = text.trim();
- const normalizedText = sanitizeUserTextForCapture(trimmed);
- const hadSanitization = normalizedText !== trimmed;
- if (!normalizedText) {
- return {
- shouldCapture: false,
- reason: /<relevant-memories>/i.test(trimmed) ? "injected_memory_context_only" : "empty_text",
- normalizedText: "",
- };
- }
-
- const compactText = normalizedText.replace(/\s+/g, "");
- const minLength = resolveCaptureMinLength(compactText);
- if (compactText.length < minLength || normalizedText.length > captureMaxLength) {
- return {
- shouldCapture: false,
- reason: "length_out_of_range",
- normalizedText,
- };
- }
-
- if (COMMAND_TEXT_RE.test(normalizedText)) {
- return {
- shouldCapture: false,
- reason: "command_text",
- normalizedText,
- };
- }
-
- if (NON_CONTENT_TEXT_RE.test(normalizedText)) {
- return {
- shouldCapture: false,
- reason: "non_content_text",
- normalizedText,
- };
- }
- if (SUBAGENT_CONTEXT_RE.test(normalizedText)) {
- return {
- shouldCapture: false,
- reason: "subagent_context",
- normalizedText,
- };
- }
- if (looksLikeQuestionOnlyText(normalizedText)) {
- return {
- shouldCapture: false,
- reason: "question_text",
- normalizedText,
- };
- }
-
- if (mode === "keyword") {
- for (const trigger of MEMORY_TRIGGERS) {
- if (trigger.test(normalizedText)) {
- return {
- shouldCapture: true,
- reason: hadSanitization
- ? `matched_trigger_after_sanitize:${trigger.toString()}`
- : `matched_trigger:${trigger.toString()}`,
- normalizedText,
- };
- }
- }
- return {
- shouldCapture: false,
- reason: hadSanitization ? "no_trigger_matched_after_sanitize" : "no_trigger_matched",
- normalizedText,
- };
- }
-
- return {
- shouldCapture: true,
- reason: hadSanitization ? "semantic_candidate_after_sanitize" : "semantic_candidate",
- normalizedText,
- };
-}
-
-function clampScore(value: number | undefined): number {
- if (typeof value !== "number" || Number.isNaN(value)) {
- return 0;
- }
- return Math.max(0, Math.min(1, value));
-}
-
-function isMemoryUri(uri: string): boolean {
- return MEMORY_URI_PATTERNS.some((pattern) => pattern.test(uri));
-}
-
-function normalizeDedupeText(text: string): string {
- return text.toLowerCase().replace(/\s+/g, " ").trim();
-}
-
-function isEventOrCaseMemory(item: FindResultItem): boolean {
- const category = (item.category ?? "").toLowerCase();
- const uri = item.uri.toLowerCase();
- return (
- category === "events" ||
- category === "cases" ||
- uri.includes("/events/") ||
- uri.includes("/cases/")
- );
-}
-
-function getMemoryDedupeKey(item: FindResultItem): string {
- const abstract = normalizeDedupeText(item.abstract ?? item.overview ?? "");
- const category = (item.category ?? "").toLowerCase() || "unknown";
- if (abstract && !isEventOrCaseMemory(item)) {
- return `abstract:${category}:${abstract}`;
- }
- return `uri:${item.uri}`;
-}
-
-function postProcessMemories(
- items: FindResultItem[],
- options: {
- limit: number;
- scoreThreshold: number;
- leafOnly?: boolean;
- },
-): FindResultItem[] {
- const deduped: FindResultItem[] = [];
- const seen = new Set<string>();
- const sorted = [...items].sort((a, b) => clampScore(b.score) - clampScore(a.score));
- for (const item of sorted) {
- if (options.leafOnly && item.is_leaf !== true) {
- continue;
- }
- if (clampScore(item.score) < options.scoreThreshold) {
- continue;
- }
- const key = getMemoryDedupeKey(item);
- if (seen.has(key)) {
- continue;
- }
- seen.add(key);
- deduped.push(item);
- if (deduped.length >= options.limit) {
- break;
- }
- }
- return deduped;
-}
-
-function formatMemoryLines(items: FindResultItem[]): string {
- return items
- .map((item, index) => {
- const score = clampScore(item.score);
- const abstract = item.abstract?.trim() || item.overview?.trim() || item.uri;
- const category = item.category ?? "memory";
- return `${index + 1}. [${category}] ${abstract} (${(score * 100).toFixed(0)}%)`;
- })
- .join("\n");
-}
-
-function trimForLog(value: string, limit = 260): string {
- const normalized = value.trim();
- if (normalized.length <= limit) {
- return normalized;
- }
- return `${normalized.slice(0, limit)}...`;
-}
-
-function toJsonLog(value: unknown, maxLen = 6000): string {
- try {
- const json = JSON.stringify(value);
- if (json.length <= maxLen) {
- return json;
- }
- return JSON.stringify({
- truncated: true,
- length: json.length,
- preview: `${json.slice(0, maxLen)}...`,
- });
- } catch {
- return JSON.stringify({ error: "stringify_failed" });
- }
-}
-
-function summarizeInjectionMemories(items: FindResultItem[]): Array<Record<string, unknown>> {
- return items.map((item) => ({
- uri: item.uri,
- category: item.category ?? null,
- abstract: trimForLog(item.abstract?.trim() || item.overview?.trim() || item.uri, 180),
- score: clampScore(item.score),
- is_leaf: item.is_leaf === true,
- }));
-}
-
-function summarizeExtractedMemories(
- items: Array<Record<string, unknown>>,
-): Array<Record<string, unknown>> {
- return items.slice(0, 10).map((item) => {
- const abstractRaw =
- typeof item.abstract === "string"
- ? item.abstract
- : typeof item.overview === "string"
- ? item.overview
- : typeof item.title === "string"
- ? item.title
- : "";
- return {
- uri: typeof item.uri === "string" ? item.uri : null,
- category: typeof item.category === "string" ? item.category : null,
- abstract: trimForLog(abstractRaw, 180),
- is_leaf: item.is_leaf === true,
- };
- });
-}
-
-function isPreferencesMemory(item: FindResultItem): boolean {
- return (
- item.category === "preferences" ||
- item.uri.includes("/preferences/") ||
- item.uri.endsWith("/preferences")
- );
-}
-
-function isEventMemory(item: FindResultItem): boolean {
- const category = (item.category ?? "").toLowerCase();
- return category === "events" || item.uri.includes("/events/");
-}
-
-function isLeafLikeMemory(item: FindResultItem): boolean {
- return item.is_leaf === true || item.uri.endsWith(".md");
-}
-
-const PREFERENCE_QUERY_RE = /prefer|preference|favorite|favourite|like|偏好|喜欢|爱好|更倾向/i;
-const TEMPORAL_QUERY_RE =
- /when|what time|date|day|month|year|yesterday|today|tomorrow|last|next|什么时候|何时|哪天|几月|几年|昨天|今天|明天|上周|下周|上个月|下个月|去年|明年/i;
-const QUERY_TOKEN_RE = /[a-z0-9]{2,}/gi;
-const QUERY_TOKEN_STOPWORDS = new Set([
- "what",
- "when",
- "where",
- "which",
- "who",
- "whom",
- "whose",
- "why",
- "how",
- "did",
- "does",
- "is",
- "are",
- "was",
- "were",
- "the",
- "and",
- "for",
- "with",
- "from",
- "that",
- "this",
- "your",
- "you",
-]);
-
-type RecallQueryProfile = {
- tokens: string[];
- wantsPreference: boolean;
- wantsTemporal: boolean;
-};
-
-function buildRecallQueryProfile(query: string): RecallQueryProfile {
- const text = query.trim();
- const allTokens = text.toLowerCase().match(QUERY_TOKEN_RE) ?? [];
- const tokens = allTokens.filter((token) => !QUERY_TOKEN_STOPWORDS.has(token));
- return {
- tokens,
- wantsPreference: PREFERENCE_QUERY_RE.test(text),
- wantsTemporal: TEMPORAL_QUERY_RE.test(text),
- };
-}
-
-function lexicalOverlapBoost(tokens: string[], text: string): number {
- if (tokens.length === 0 || !text) {
- return 0;
- }
- const haystack = ` ${text.toLowerCase()} `;
- let matched = 0;
- for (const token of tokens.slice(0, 8)) {
- if (haystack.includes(` ${token} `) || haystack.includes(token)) {
- matched += 1;
- }
- }
- return Math.min(0.2, (matched / Math.min(tokens.length, 4)) * 0.2);
-}
-
-function rankForInjection(item: FindResultItem, query: RecallQueryProfile): number {
- // Keep ranking simple and stable: semantic score + light query-aware boosts.
- const baseScore = clampScore(item.score);
- const abstract = (item.abstract ?? item.overview ?? "").trim();
- const leafBoost = isLeafLikeMemory(item) ? 0.12 : 0;
- const eventBoost = query.wantsTemporal && isEventMemory(item) ? 0.1 : 0;
- const preferenceBoost = query.wantsPreference && isPreferencesMemory(item) ? 0.08 : 0;
- const overlapBoost = lexicalOverlapBoost(query.tokens, `${item.uri} ${abstract}`);
- return baseScore + leafBoost + eventBoost + preferenceBoost + overlapBoost;
-}
-
-function pickMemoriesForInjection(
- items: FindResultItem[],
- limit: number,
- queryText: string,
-): FindResultItem[] {
- if (items.length === 0 || limit <= 0) {
- return [];
- }
-
- const query = buildRecallQueryProfile(queryText);
- const sorted = [...items].sort((a, b) => rankForInjection(b, query) - rankForInjection(a, query));
- const deduped: FindResultItem[] = [];
- const seen = new Set<string>();
- for (const item of sorted) {
- const abstractKey = (item.abstract ?? item.overview ?? "").trim().toLowerCase();
- const key = abstractKey || item.uri;
- if (seen.has(key)) {
- continue;
- }
- seen.add(key);
- deduped.push(item);
- }
- const leaves = deduped.filter((item) => isLeafLikeMemory(item));
- if (leaves.length >= limit) {
- return leaves.slice(0, limit);
- }
-
- const picked = [...leaves];
- const used = new Set(leaves.map((item) => item.uri));
- for (const item of deduped) {
- if (picked.length >= limit) {
- break;
- }
- if (used.has(item.uri)) {
- continue;
- }
- picked.push(item);
- }
- return picked;
-}
-
-class OpenVikingClient {
- private readonly resolvedSpaceByScope: Partial<Record<ScopeName, string>> = {};
- private runtimeIdentity: RuntimeIdentity | null = null;
-
- constructor(
- private readonly baseUrl: string,
- private readonly apiKey: string,
- private readonly timeoutMs: number,
- ) {}
-
- private async request<T>(path: string, init: RequestInit = {}): Promise<T> {
- const controller = new AbortController();
- const timer = setTimeout(() => controller.abort(), this.timeoutMs);
- try {
- const headers = new Headers(init.headers ?? {});
- if (this.apiKey) {
- headers.set("X-API-Key", this.apiKey);
- }
- if (init.body && !headers.has("Content-Type")) {
- headers.set("Content-Type", "application/json");
- }
-
- const response = await fetch(`${this.baseUrl}${path}`, {
- ...init,
- headers,
- signal: controller.signal,
- });
-
- const payload = (await response.json().catch(() => ({}))) as {
- status?: string;
- result?: T;
- error?: { code?: string; message?: string };
- };
-
- if (!response.ok || payload.status === "error") {
- const code = payload.error?.code ? ` [${payload.error.code}]` : "";
- const message = payload.error?.message ?? `HTTP ${response.status}`;
- throw new Error(`OpenViking request failed${code}: ${message}`);
- }
-
- return (payload.result ?? payload) as T;
- } finally {
- clearTimeout(timer);
- }
- }
-
- async healthCheck(): Promise<void> {
- await this.request<{ status: string }>("/health");
- }
-
- private async ls(uri: string): Promise<Array<Record<string, unknown>>> {
- return this.request<Array<Record<string, unknown>>>(
- `/api/v1/fs/ls?uri=${encodeURIComponent(uri)}&output=original`,
- );
- }
-
- private async getRuntimeIdentity(): Promise<RuntimeIdentity> {
- if (this.runtimeIdentity) {
- return this.runtimeIdentity;
- }
- const fallback: RuntimeIdentity = { userId: "default", agentId: "default" };
- try {
- const status = await this.request<{ user?: unknown }>("/api/v1/system/status");
- const userId =
- typeof status.user === "string" && status.user.trim() ? status.user.trim() : "default";
- this.runtimeIdentity = { userId, agentId: "default" };
- return this.runtimeIdentity;
- } catch {
- this.runtimeIdentity = fallback;
- return fallback;
- }
- }
-
- private async resolveScopeSpace(scope: ScopeName): Promise<string> {
- const cached = this.resolvedSpaceByScope[scope];
- if (cached) {
- return cached;
- }
-
- const identity = await this.getRuntimeIdentity();
- const fallbackSpace =
- scope === "user" ? identity.userId : md5Short(`${identity.userId}${identity.agentId}`);
- const reservedDirs = scope === "user" ? USER_STRUCTURE_DIRS : AGENT_STRUCTURE_DIRS;
- const preferredSpace =
- scope === "user" ? identity.userId : md5Short(`${identity.userId}${identity.agentId}`);
-
- try {
- const entries = await this.ls(`viking://${scope}`);
- const spaces = entries
- .filter((entry) => entry?.isDir === true)
- .map((entry) => (typeof entry.name === "string" ? entry.name.trim() : ""))
- .filter((name) => name && !name.startsWith(".") && !reservedDirs.has(name));
-
- if (spaces.length > 0) {
- if (spaces.includes(preferredSpace)) {
- this.resolvedSpaceByScope[scope] = preferredSpace;
- return preferredSpace;
- }
- if (scope === "user" && spaces.includes("default")) {
- this.resolvedSpaceByScope[scope] = "default";
- return "default";
- }
- if (spaces.length === 1) {
- this.resolvedSpaceByScope[scope] = spaces[0]!;
- return spaces[0]!;
- }
- }
- } catch {
- // Fall back to identity-derived space when listing fails.
- }
-
- this.resolvedSpaceByScope[scope] = fallbackSpace;
- return fallbackSpace;
- }
-
- private async normalizeTargetUri(targetUri: string): Promise<string> {
- const trimmed = targetUri.trim().replace(/\/+$/, "");
- const match = trimmed.match(/^viking:\/\/(user|agent)(?:\/(.*))?$/);
- if (!match) {
- return trimmed;
- }
- const scope = match[1] as ScopeName;
- const rawRest = (match[2] ?? "").trim();
- if (!rawRest) {
- return trimmed;
- }
- const parts = rawRest.split("/").filter(Boolean);
- if (parts.length === 0) {
- return trimmed;
- }
-
- const reservedDirs = scope === "user" ? USER_STRUCTURE_DIRS : AGENT_STRUCTURE_DIRS;
- if (!reservedDirs.has(parts[0]!)) {
- return trimmed;
- }
-
- const space = await this.resolveScopeSpace(scope);
- return `viking://${scope}/${space}/${parts.join("/")}`;
- }
-
- async find(
- query: string,
- options: {
- targetUri: string;
- limit: number;
- scoreThreshold?: number;
- sessionId?: string;
- },
- ): Promise<FindResult> {
- const normalizedTargetUri = await this.normalizeTargetUri(options.targetUri);
- const body = {
- query,
- target_uri: normalizedTargetUri,
- limit: options.limit,
- score_threshold: options.scoreThreshold,
- session_id: options.sessionId,
- };
- return this.request<FindResult>("/api/v1/search/search", {
- method: "POST",
- body: JSON.stringify(body),
- });
- }
-
- async createSession(): Promise<string> {
- const result = await this.request<{ session_id: string }>("/api/v1/sessions", {
- method: "POST",
- body: JSON.stringify({}),
- });
- return result.session_id;
- }
-
- async addSessionMessage(sessionId: string, role: string, content: string): Promise<void> {
- await this.request<{ session_id: string }>(
- `/api/v1/sessions/${encodeURIComponent(sessionId)}/messages`,
- {
- method: "POST",
- body: JSON.stringify({ role, content }),
- },
- );
- }
-
- /** GET session so server loads messages from storage before extract (workaround for AGFS visibility). */
- async getSession(sessionId: string): Promise<{ message_count?: number }> {
- return this.request<{ message_count?: number }>(
- `/api/v1/sessions/${encodeURIComponent(sessionId)}`,
- { method: "GET" },
- );
- }
-
- async extractSessionMemories(sessionId: string): Promise<Array<Record<string, unknown>>> {
- return this.request<Array<Record<string, unknown>>>(
- `/api/v1/sessions/${encodeURIComponent(sessionId)}/extract`,
- { method: "POST", body: JSON.stringify({}) },
- );
- }
-
- async deleteSession(sessionId: string): Promise<void> {
- await this.request(`/api/v1/sessions/${encodeURIComponent(sessionId)}`, { method: "DELETE" });
- }
-
- async deleteUri(uri: string): Promise<void> {
- await this.request(`/api/v1/fs?uri=${encodeURIComponent(uri)}&recursive=false`, {
- method: "DELETE",
- });
- }
-}
-
-function extractTextsFromUserMessages(messages: unknown[]): string[] {
- const texts: string[] = [];
- for (const msg of messages) {
- if (!msg || typeof msg !== "object") {
- continue;
- }
- const msgObj = msg as Record<string, unknown>;
- if (msgObj.role !== "user") {
- continue;
- }
- const content = msgObj.content;
- if (typeof content === "string") {
- texts.push(content);
- continue;
- }
- if (Array.isArray(content)) {
- for (const block of content) {
- if (!block || typeof block !== "object") {
- continue;
- }
- const blockObj = block as Record<string, unknown>;
- if (blockObj.type === "text" && typeof blockObj.text === "string") {
- texts.push(blockObj.text);
- }
- }
- }
- }
- return texts;
-}
-
-function extractLatestUserText(messages: unknown[] | undefined): string {
- if (!messages || messages.length === 0) {
- return "";
- }
- const texts = extractTextsFromUserMessages(messages);
- for (let i = texts.length - 1; i >= 0; i -= 1) {
- const normalized = sanitizeUserTextForCapture(texts[i] ?? "");
- if (normalized) {
- return normalized;
- }
- }
- return "";
-}
-
-function waitForHealth(baseUrl: string, timeoutMs: number, intervalMs: number): Promise<void> {
- const deadline = Date.now() + timeoutMs;
- return new Promise((resolve, reject) => {
- const tick = () => {
- if (Date.now() > deadline) {
- reject(new Error(`OpenViking health check timeout at ${baseUrl}`));
- return;
- }
- fetch(`${baseUrl}/health`)
- .then((r) => r.json())
- .then((body: { status?: string }) => {
- if (body?.status === "ok") {
- resolve();
- return;
- }
- setTimeout(tick, intervalMs);
- })
- .catch(() => setTimeout(tick, intervalMs));
- };
- tick();
- });
-}
-
-function withTimeout<T>(promise: Promise<T>, timeoutMs: number, timeoutMessage: string): Promise<T> {
- return new Promise((resolve, reject) => {
- const timer = setTimeout(() => reject(new Error(timeoutMessage)), timeoutMs);
- promise.then(
- (value) => {
- clearTimeout(timer);
- resolve(value);
- },
- (err) => {
- clearTimeout(timer);
- reject(err);
- },
- );
- });
-}
-
-function quickTcpProbe(host: string, port: number, timeoutMs: number): Promise<boolean> {
- return new Promise((resolve) => {
- const socket = new Socket();
- let done = false;
- const finish = (ok: boolean) => {
- if (done) {
- return;
- }
- done = true;
- socket.destroy();
- resolve(ok);
- };
- socket.setTimeout(timeoutMs);
- socket.once("connect", () => finish(true));
- socket.once("timeout", () => finish(false));
- socket.once("error", () => finish(false));
- try {
- socket.connect(port, host);
- } catch {
- finish(false);
- }
- });
-}
-
-async function quickHealthCheck(baseUrl: string, timeoutMs: number): Promise<boolean> {
- const controller = new AbortController();
- const timer = setTimeout(() => controller.abort(), timeoutMs);
- try {
- const response = await fetch(`${baseUrl}/health`, {
- method: "GET",
- signal: controller.signal,
- });
- if (!response.ok) {
- return false;
- }
- const body = (await response.json().catch(() => ({}))) as { status?: string };
- return body.status === "ok";
- } catch {
- return false;
- } finally {
- clearTimeout(timer);
- }
-}
-
-async function quickRecallPrecheck(
- mode: "local" | "remote",
- baseUrl: string,
- defaultPort: number,
- localProcess: ReturnType<typeof spawn> | null,
-): Promise<{ ok: true } | { ok: false; reason: string }> {
- const healthOk = await quickHealthCheck(baseUrl, 500);
- if (healthOk) {
- return { ok: true };
- }
-
- let host = "127.0.0.1";
- let port = defaultPort;
- try {
- const parsed = new URL(baseUrl);
- if (parsed.hostname) {
- host = parsed.hostname;
- }
- if (parsed.port) {
- const parsedPort = Number(parsed.port);
- if (Number.isFinite(parsedPort) && parsedPort > 0) {
- port = parsedPort;
- }
- }
- } catch {
- // Keep defaults when baseUrl is malformed.
- }
-
- if (mode === "local") {
- const portOk = await quickTcpProbe(host, port, 200);
- if (!portOk) {
- return { ok: false, reason: `local port unavailable (${host}:${port})` };
- }
- if (localProcess && (localProcess.killed || localProcess.exitCode !== null || localProcess.signalCode !== null)) {
- return { ok: false, reason: "local process is not running" };
- }
- }
- return { ok: false, reason: "health check failed" };
-}
+import { OpenVikingClient, localClientCache, isMemoryUri } from "./client.js";
+import type { FindResultItem } from "./client.js";
+import {
+ getCaptureDecision,
+ isTranscriptLikeIngest,
+ extractNewTurnTexts,
+ extractLatestUserText,
+} from "./text-utils.js";
+import {
+ clampScore,
+ postProcessMemories,
+ formatMemoryLines,
+ trimForLog,
+ toJsonLog,
+ summarizeInjectionMemories,
+ summarizeExtractedMemories,
+ pickMemoriesForInjection,
+} from "./memory-ranking.js";
+import {
+ IS_WIN,
+ waitForHealth,
+ withTimeout,
+ quickRecallPrecheck,
+ quickHealthCheck,
+ quickTcpProbe,
+ resolvePythonCommand,
+} from "./process-manager.js";
const memoryPlugin = {
id: "memory-openviking",
@@ -1032,7 +79,7 @@ const memoryPlugin = {
});
}
} else {
- clientPromise = Promise.resolve(new OpenVikingClient(cfg.baseUrl, cfg.apiKey, cfg.timeoutMs));
+ clientPromise = Promise.resolve(new OpenVikingClient(cfg.baseUrl, cfg.apiKey, cfg.agentId, cfg.timeoutMs));
}
const getClient = (): Promise<OpenVikingClient> => clientPromise;
@@ -1055,7 +102,7 @@ const memoryPlugin = {
Type.String({ description: "Search scope URI (default: plugin config)" }),
),
}),
- async execute(_toolCallId, params) {
+ async execute(_toolCallId: string, params: Record<string, unknown>) {
const { query } = params as { query: string };
const limit =
typeof (params as { limit?: number }).limit === "number"
@@ -1068,13 +115,45 @@ const memoryPlugin = {
const targetUri =
typeof (params as { targetUri?: string }).targetUri === "string"
? (params as { targetUri: string }).targetUri
- : cfg.targetUri;
- const requestLimit = Math.max(limit * 4, limit);
- const result = await (await getClient()).find(query, {
- targetUri,
- limit: requestLimit,
- scoreThreshold: 0,
- });
+ : undefined;
+ const requestLimit = Math.max(limit * 4, 20);
+
+ let result;
+ if (targetUri) {
+ // 如果指定了目标 URI,只检索该位置
+ result = await (await getClient()).find(query, {
+ targetUri,
+ limit: requestLimit,
+ scoreThreshold: 0,
+ });
+ } else {
+ // 默认同时检索 user 和 agent 两个位置的记忆
+ const [userSettled, agentSettled] = await Promise.allSettled([
+ (await getClient()).find(query, {
+ targetUri: "viking://user/memories",
+ limit: requestLimit,
+ scoreThreshold: 0,
+ }),
+ (await getClient()).find(query, {
+ targetUri: "viking://agent/memories",
+ limit: requestLimit,
+ scoreThreshold: 0,
+ }),
+ ]);
+ const userResult = userSettled.status === "fulfilled" ? userSettled.value : { memories: [] };
+ const agentResult = agentSettled.status === "fulfilled" ? agentSettled.value : { memories: [] };
+ // 合并两个位置的结果,去重
+ const allMemories = [...(userResult.memories ?? []), ...(agentResult.memories ?? [])];
+ const uniqueMemories = allMemories.filter((memory, index, self) =>
+ index === self.findIndex((m) => m.uri === memory.uri)
+ );
+ const leafOnly = uniqueMemories.filter((m) => m.level === 2);
+ result = {
+ memories: leafOnly,
+ total: leafOnly.length,
+ };
+ }
+
const memories = postProcessMemories(result.memories ?? [], {
limit,
scoreThreshold,
@@ -1116,7 +195,7 @@ const memoryPlugin = {
role: Type.Optional(Type.String({ description: "Session role, default user" })),
sessionId: Type.Optional(Type.String({ description: "Existing OpenViking session ID" })),
}),
- async execute(_toolCallId, params) {
+ async execute(_toolCallId: string, params: Record<string, unknown>) {
const { text } = params as { text: string };
const role =
typeof (params as { role?: string }).role === "string"
@@ -1186,7 +265,7 @@ const memoryPlugin = {
Type.Number({ description: "Minimum score (0-1, default: plugin config)" }),
),
}),
- async execute(_toolCallId, params) {
+ async execute(_toolCallId: string, params: Record<string, unknown>) {
const uri = (params as { uri?: string }).uri;
if (uri) {
if (!isMemoryUri(uri)) {
@@ -1273,7 +352,7 @@ const memoryPlugin = {
);
if (cfg.autoRecall || cfg.ingestReplyAssist) {
- api.on("before_agent_start", async (event) => {
+ api.on("before_agent_start", async (event: { messages?: unknown[]; prompt: string }) => {
const queryText = extractLatestUserText(event.messages) || event.prompt.trim();
if (!queryText) {
return;
@@ -1288,27 +367,62 @@ const memoryPlugin = {
);
} else {
try {
- const candidateLimit = Math.max(cfg.recallLimit * 4, cfg.recallLimit);
- const result = await withTimeout(
+ const candidateLimit = Math.max(cfg.recallLimit * 4, 20);
+ // 同时检索 user 和 agent 两个位置的记忆
+ const [userSettled, agentSettled] = await Promise.allSettled([
getClient().then((client) =>
client.find(queryText, {
- targetUri: cfg.targetUri,
+ targetUri: "viking://user/memories",
limit: candidateLimit,
scoreThreshold: 0,
}),
),
- autoRecallTimeoutMs,
- `OpenViking auto-recall timeout after ${autoRecallTimeoutMs}ms`,
+ getClient().then((client) =>
+ client.find(queryText, {
+ targetUri: "viking://agent/memories",
+ limit: candidateLimit,
+ scoreThreshold: 0,
+ }),
+ ),
+ ]);
+ const userResult = userSettled.status === "fulfilled" ? userSettled.value : { memories: [] };
+ const agentResult = agentSettled.status === "fulfilled" ? agentSettled.value : { memories: [] };
+ if (userSettled.status === "rejected") {
+ api.logger.warn(`memory-openviking: user memories search failed: ${String(userSettled.reason)}`);
+ }
+ if (agentSettled.status === "rejected") {
+ api.logger.warn(`memory-openviking: agent memories search failed: ${String(agentSettled.reason)}`);
+ }
+ // 合并两个位置的结果,去重
+ const allMemories = [...(userResult.memories ?? []), ...(agentResult.memories ?? [])];
+ const uniqueMemories = allMemories.filter((memory, index, self) =>
+ index === self.findIndex((m) => m.uri === memory.uri)
);
- const processed = postProcessMemories(result.memories ?? [], {
+ const leafOnly = uniqueMemories.filter((m) => m.level === 2);
+ const processed = postProcessMemories(leafOnly, {
limit: candidateLimit,
scoreThreshold: cfg.recallScoreThreshold,
});
const memories = pickMemoriesForInjection(processed, cfg.recallLimit, queryText);
if (memories.length > 0) {
- const memoryContext = memories
- .map((item) => `- [${item.category ?? "memory"}] ${item.abstract ?? item.uri}`)
- .join("\n");
+ // 对 level 2 节点读取正文,其余用 abstract
+ const client = await getClient();
+ const memoryLines = await Promise.all(
+ memories.map(async (item: FindResultItem) => {
+ if (item.level === 2) {
+ try {
+ const content = await client.read(item.uri);
+ if (content && typeof content === "string" && content.trim()) {
+ return `- [${item.category ?? "memory"}] ${content.trim()}`;
+ }
+ } catch {
+ // fallback to abstract
+ }
+ }
+ return `- [${item.category ?? "memory"}] ${item.abstract ?? item.uri}`;
+ }),
+ );
+ const memoryContext = memoryLines.join("\n");
api.logger.info?.(
`memory-openviking: injecting ${memories.length} memories into context`,
);
@@ -1356,7 +470,9 @@ const memoryPlugin = {
}
if (cfg.autoCapture) {
- api.on("agent_end", async (event) => {
+ let lastProcessedMsgCount = 0;
+
+ api.on("agent_end", async (event: { success?: boolean; messages?: unknown[] }) => {
if (!event.success || !event.messages || event.messages.length === 0) {
api.logger.info(
`memory-openviking: auto-capture skipped (success=${String(event.success)}, messages=${event.messages?.length ?? 0})`,
@@ -1364,52 +480,43 @@ const memoryPlugin = {
return;
}
try {
- const texts = extractTextsFromUserMessages(event.messages);
+ const messages = event.messages;
+ const { texts: newTexts, newCount } = extractNewTurnTexts(messages, lastProcessedMsgCount);
+ lastProcessedMsgCount = messages.length;
+
+ if (newTexts.length === 0) {
+ api.logger.info("memory-openviking: auto-capture skipped (no new user/assistant messages)");
+ return;
+ }
+
+ // 合并当前轮的 user+assistant 为一个文本块
+ const turnText = newTexts.join("\n");
+
+ // 对合并文本做 capture decision(主要检查长度和命令过滤)
+ const decision = getCaptureDecision(turnText, cfg.captureMode, cfg.captureMaxLength);
+ const preview = turnText.length > 80 ? `${turnText.slice(0, 80)}...` : turnText;
api.logger.info(
- `memory-openviking: auto-capture evaluating ${texts.length} text candidates`,
+ `memory-openviking: capture-check shouldCapture=${String(decision.shouldCapture)} reason=${decision.reason} newMsgCount=${newCount} text="${preview}"`,
);
- const decisions = texts
- .map((text) => {
- const decision = getCaptureDecision(text, cfg.captureMode, cfg.captureMaxLength);
- return {
- captureText: decision.normalizedText,
- decision,
- };
- })
- .filter((item) => item.captureText);
- for (const item of decisions.slice(0, 5)) {
- const preview =
- item.captureText.length > 80
- ? `${item.captureText.slice(0, 80)}...`
- : item.captureText;
- api.logger.info(
- `memory-openviking: capture-check shouldCapture=${String(item.decision.shouldCapture)} reason=${item.decision.reason} text="${preview}"`,
- );
- }
- const toCapture = decisions
- .filter((item) => item.decision.shouldCapture)
- .map((item) => item.captureText);
- const selected = pickRecentUniqueTexts(toCapture, CAPTURE_LIMIT);
- if (selected.length === 0) {
- api.logger.info("memory-openviking: auto-capture skipped (no matched texts)");
+ if (!decision.shouldCapture) {
+ api.logger.info("memory-openviking: auto-capture skipped (capture decision rejected)");
return;
}
+
const c = await getClient();
const sessionId = await c.createSession();
try {
- for (const text of selected) {
- await c.addSessionMessage(sessionId, "user", text);
- }
+ await c.addSessionMessage(sessionId, "user", decision.normalizedText);
// Force server to read session so storage (e.g. AGFS) sees the written messages before extract
await c.getSession(sessionId).catch(() => ({}));
const extracted = await c.extractSessionMemories(sessionId);
api.logger.info(
- `memory-openviking: auto-captured ${selected.length} messages, extracted ${extracted.length} memories`,
+ `memory-openviking: auto-captured ${newCount} new messages, extracted ${extracted.length} memories`,
);
api.logger.info(
`memory-openviking: capture-detail ${toJsonLog({
- capturedCount: selected.length,
- captured: selected.map((text) => trimForLog(text, 260)),
+ capturedCount: newCount,
+ captured: [trimForLog(turnText, 260)],
extractedCount: extracted.length,
extracted: summarizeExtractedMemories(extracted),
})}`,
@@ -1435,113 +542,33 @@ const memoryPlugin = {
const baseUrl = cfg.baseUrl;
const timeoutMs = 60_000;
const intervalMs = 500;
- const defaultPy = IS_WIN ? "python" : "python3";
- let pythonCmd = process.env.OPENVIKING_PYTHON;
- if (!pythonCmd) {
- if (IS_WIN) {
- const envBat = join(homedir(), ".openclaw", "openviking.env.bat");
- if (existsSync(envBat)) {
- try {
- const content = readFileSync(envBat, "utf-8");
- const m = content.match(/set\s+OPENVIKING_PYTHON=(.+)/i);
- if (m?.[1]) pythonCmd = m[1].trim();
- } catch { /* ignore */ }
- }
- } else {
- const envFile = join(homedir(), ".openclaw", "openviking.env");
- if (existsSync(envFile)) {
- try {
- const content = readFileSync(envFile, "utf-8");
- const m = content.match(/OPENVIKING_PYTHON=['"]([^'"]+)['"]/);
- if (m?.[1]) pythonCmd = m[1];
- } catch {
- /* ignore */
- }
- }
- }
- }
- if (!pythonCmd) {
- if (IS_WIN) {
- try {
- pythonCmd = execSync("where python", { encoding: "utf-8", shell: true }).split(/\r?\n/)[0].trim();
- } catch {
- pythonCmd = "python";
- }
- } else {
- try {
- pythonCmd = execSync("command -v python3 || which python3", {
- encoding: "utf-8",
- env: process.env,
- shell: "/bin/sh",
- }).trim();
- } catch {
- pythonCmd = "python3";
- }
- }
- }
- if (pythonCmd === defaultPy) {
- api.logger.warn?.(
- `memory-openviking: 未解析到 ${defaultPy} 路径,将用 "${defaultPy}"。若 openviking 在自定义 Python 下,请设置 OPENVIKING_PYTHON` +
- (IS_WIN ? ' 或 call "%USERPROFILE%\\.openclaw\\openviking.env.bat"' : " 或 source ~/.openclaw/openviking.env"),
+ // 1. Check if a healthy OpenViking is already running on this port — reuse it
+ const existingHealthy = await quickHealthCheck(baseUrl, 2000);
+ if (existingHealthy) {
+ const client = new OpenVikingClient(baseUrl, cfg.apiKey, cfg.agentId, cfg.timeoutMs);
+ localClientCache.set(localCacheKey, { client, process: null });
+ resolveLocalClient(client);
+ rejectLocalClient = null;
+ api.logger.info(
+ `memory-openviking: reusing existing server at ${baseUrl}`,
);
+ return;
}
- // Kill stale OpenViking and AGFS processes occupying configured ports (so port changes are respected)
- const agfsPort = getAgfsPortFromConfig(cfg.configPath);
- const portsToClean = [cfg.port];
- if (agfsPort !== cfg.port) portsToClean.push(agfsPort);
- if (IS_WIN) {
- for (const port of portsToClean) {
- try {
- const netstatOut = execSync(`netstat -ano | findstr "LISTENING" | findstr ":${port}"`, {
- encoding: "utf-8", shell: true,
- }).trim();
- if (netstatOut) {
- const pids = new Set<number>();
- for (const line of netstatOut.split(/\r?\n/)) {
- const m = line.trim().match(/\s(\d+)\s*$/);
- if (m) pids.add(Number(m[1]));
- }
- for (const pid of pids) {
- if (pid > 0) {
- api.logger.info?.(`memory-openviking: killing stale process on port ${port} (pid ${pid})`);
- try { execSync(`taskkill /PID ${pid} /F`, { shell: true }); } catch { /* already gone */ }
- }
- }
- await new Promise((r) => setTimeout(r, 500));
- }
- } catch { /* netstat not available or no stale process */ }
- }
- } else {
- for (const port of portsToClean) {
- try {
- let pids: number[] = [];
- try {
- const lsofOut = execSync(`lsof -ti tcp:${port} -s tcp:listen 2>/dev/null || true`, {
- encoding: "utf-8",
- shell: "/bin/sh",
- }).trim();
- if (lsofOut) pids = lsofOut.split(/\s+/).map((s) => Number(s)).filter((n) => n > 0);
- } catch { /* lsof not available */ }
- if (pids.length === 0) {
- const ssOut = execSync(`ss -tlnp 2>/dev/null | awk -v p=":${port}" '$4 ~ p {gsub(/.*pid=/,""); gsub(/,.*/,""); print; exit}'`, {
- encoding: "utf-8",
- shell: "/bin/sh",
- }).trim();
- if (ssOut) {
- const n = Number(ssOut);
- if (n > 0) pids = [n];
- }
- }
- for (const pid of pids) {
- api.logger.info?.(`memory-openviking: killing stale process on port ${port} (pid ${pid})`);
- try { process.kill(pid, "SIGKILL"); } catch { /* already gone */ }
- }
- if (pids.length) await new Promise((r) => setTimeout(r, 500));
- } catch { /* port check failed */ }
- }
+ // 2. Check if port is occupied by something else
+ const portOccupied = await quickTcpProbe("127.0.0.1", cfg.port, 500);
+ if (portOccupied) {
+ const msg = `memory-openviking: port ${cfg.port} is occupied by another process (not OpenViking). ` +
+ `Change the port in your plugin config or ov.conf, e.g.: ` +
+ `openclaw config set plugins.entries.memory-openviking.config.port 1934`;
+ api.logger.warn(msg);
+ markLocalUnavailable("port occupied", new Error(msg));
+ throw new Error(msg);
}
+ // 3. Port is free — start OpenViking
+ const pythonCmd = resolvePythonCommand(api.logger);
+
// Inherit system environment; optionally override Go/Python paths via env vars
const pathSep = IS_WIN ? ";" : ":";
const env = {
@@ -1558,9 +585,7 @@ const memoryPlugin = {
};
// Run OpenViking server: use run_path on the module file to avoid RuntimeWarning from
// "parent package import loads submodule before execution" (exit 3). Fallback to run_module with warning suppressed.
- const runpyCode = IS_WIN
- ? `import sys,os,warnings; warnings.filterwarnings('ignore', category=RuntimeWarning, message='.*sys.modules.*'); sys.argv=['openviking.server.bootstrap','--config',os.environ['OPENVIKING_START_CONFIG'],'--host',os.environ.get('OPENVIKING_START_HOST','127.0.0.1'),'--port',os.environ['OPENVIKING_START_PORT']]; import runpy, importlib.util; spec=importlib.util.find_spec('openviking.server.bootstrap'); (runpy.run_path(spec.origin, run_name='__main__') if spec and getattr(spec,'origin',None) else runpy.run_module('openviking.server.bootstrap', run_name='__main__', alter_sys=True))`
- : `import sys,os,warnings; warnings.filterwarnings('ignore', category=RuntimeWarning, message='.*sys.modules.*'); sys.argv=['openviking.server.bootstrap','--config',os.environ['OPENVIKING_START_CONFIG'],'--host',os.environ.get('OPENVIKING_START_HOST','127.0.0.1'),'--port',os.environ['OPENVIKING_START_PORT']]; import runpy, importlib.util; spec=importlib.util.find_spec('openviking.server.bootstrap'); (runpy.run_path(spec.origin, run_name='__main__') if spec and getattr(spec,'origin',None) else runpy.run_module('openviking.server.bootstrap', run_name='__main__', alter_sys=True))`;
+ const runpyCode = `import sys,os,warnings; warnings.filterwarnings('ignore', category=RuntimeWarning, message='.*sys.modules.*'); sys.argv=['openviking.server.bootstrap','--config',os.environ['OPENVIKING_START_CONFIG'],'--host',os.environ.get('OPENVIKING_START_HOST','127.0.0.1'),'--port',os.environ['OPENVIKING_START_PORT']]; import runpy, importlib.util; spec=importlib.util.find_spec('openviking.server.bootstrap'); (runpy.run_path(spec.origin, run_name='__main__') if spec and getattr(spec,'origin',None) else runpy.run_module('openviking.server.bootstrap', run_name='__main__', alter_sys=True))`;
const child = spawn(
pythonCmd,
["-c", runpyCode],
@@ -1568,13 +593,13 @@ const memoryPlugin = {
);
localProcess = child;
const stderrChunks: string[] = [];
- child.on("error", (err) => api.logger.warn(`memory-openviking: local server error: ${String(err)}`));
- child.stderr?.on("data", (chunk) => {
+ child.on("error", (err: Error) => api.logger.warn(`memory-openviking: local server error: ${String(err)}`));
+ child.stderr?.on("data", (chunk: Buffer) => {
const s = String(chunk).trim();
if (s) stderrChunks.push(s);
api.logger.debug?.(`[openviking] ${s}`);
});
- child.on("exit", (code, signal) => {
+ child.on("exit", (code: number | null, signal: string | null) => {
if (localProcess === child && (code != null && code !== 0 || signal)) {
const out = stderrChunks.length ? `\n[openviking stderr]\n${stderrChunks.join("\n")}` : "";
api.logger.warn(`memory-openviking: subprocess exited (code=${code}, signal=${signal})${out}`);
@@ -1582,7 +607,7 @@ const memoryPlugin = {
});
try {
await waitForHealth(baseUrl, timeoutMs, intervalMs);
- const client = new OpenVikingClient(baseUrl, cfg.apiKey, cfg.timeoutMs);
+ const client = new OpenVikingClient(baseUrl, cfg.apiKey, cfg.agentId, cfg.timeoutMs);
localClientCache.set(localCacheKey, { client, process: child });
resolveLocalClient(client);
rejectLocalClient = null;
diff --git a/examples/openclaw-memory-plugin/install.ps1 b/examples/openclaw-memory-plugin/install.ps1
index d18c21a95..633c44e11 100644
--- a/examples/openclaw-memory-plugin/install.ps1
+++ b/examples/openclaw-memory-plugin/install.ps1
@@ -1,6 +1,7 @@
param(
[switch]$Yes,
- [switch]$Zh
+ [switch]$Zh,
+ [string]$Workdir = ""
)
$ErrorActionPreference = "Stop"
@@ -33,9 +34,10 @@ $NpmRegistry = if ($env:NPM_REGISTRY) { $env:NPM_REGISTRY } else { "https://regi
$PipIndexUrl = if ($env:PIP_INDEX_URL) { $env:PIP_INDEX_URL } else { "https://pypi.tuna.tsinghua.edu.cn/simple" }
$HomeDir = if ($env:USERPROFILE) { $env:USERPROFILE } else { $HOME }
-$OpenClawDir = Join-Path $HomeDir ".openclaw"
+$OpenClawDir = if ($Workdir) { $Workdir } else { Join-Path $HomeDir ".openclaw" }
$OpenVikingDir = Join-Path $HomeDir ".openviking"
$PluginDest = Join-Path $OpenClawDir "extensions\memory-openviking"
+$SelectedMode = "local"
$DefaultServerPort = 1933
$DefaultAgfsPort = 1833
@@ -186,6 +188,64 @@ function Prompt-Optional {
return $v.Trim()
}
+function Select-Workdir {
+ # Already set via -Workdir
+ $defaultDir = Join-Path $HomeDir ".openclaw"
+ if ($OpenClawDir -ne $defaultDir) { return }
+
+ $instances = @()
+ Get-ChildItem -Path $HomeDir -Directory -Filter ".openclaw*" -ErrorAction SilentlyContinue | ForEach-Object {
+ $name = $_.Name
+ if ($name -eq ".openclaw" -or $name -like ".openclaw-*") {
+ $instances += $_.FullName
+ }
+ }
+
+ if ($instances.Count -le 1) { return }
+
+ if (-not $Yes) {
+ Write-Host ""
+ Title (T "Found multiple OpenClaw instances:" "发现多个 OpenClaw 实例:")
+ for ($i = 0; $i -lt $instances.Count; $i++) {
+ Write-Host " $($i + 1)) $($instances[$i])"
+ }
+ Write-Host ""
+ $choice = Prompt-OrDefault (T "Select instance number" "选择实例编号") "1"
+ $idx = [int]$choice - 1
+ if ($idx -ge 0 -and $idx -lt $instances.Count) {
+ $script:OpenClawDir = $instances[$idx]
+ } else {
+ Warn (T "Invalid selection, using default" "无效选择,使用默认")
+ $script:OpenClawDir = $instances[0]
+ }
+ $script:PluginDest = Join-Path $script:OpenClawDir "extensions\memory-openviking"
+ }
+}
+
+function Select-Mode {
+ if ($Yes) {
+ $script:SelectedMode = "local"
+ return
+ }
+ $mode = Prompt-OrDefault (T "Plugin mode (local/remote)" "插件模式 (local/remote)") "local"
+ if ($mode -eq "remote") {
+ $script:SelectedMode = "remote"
+ } else {
+ $script:SelectedMode = "local"
+ }
+}
+
+function Collect-RemoteConfig {
+ $script:RemoteBaseUrl = "http://127.0.0.1:1933"
+ $script:RemoteApiKey = ""
+ $script:RemoteAgentId = ""
+ if (-not $Yes) {
+ $script:RemoteBaseUrl = Prompt-OrDefault (T "OpenViking server URL" "OpenViking 服务器地址") $script:RemoteBaseUrl
+ $script:RemoteApiKey = Prompt-Optional (T "API Key (optional)" "API Key(可选)")
+ $script:RemoteAgentId = Prompt-Optional (T "Agent ID (optional)" "Agent ID(可选)")
+ }
+}
+
function Configure-OvConf {
New-Item -ItemType Directory -Force -Path $OpenVikingDir | Out-Null
@@ -259,6 +319,10 @@ function Download-Plugin {
$files = @(
"examples/openclaw-memory-plugin/index.ts",
"examples/openclaw-memory-plugin/config.ts",
+ "examples/openclaw-memory-plugin/client.ts",
+ "examples/openclaw-memory-plugin/process-manager.ts",
+ "examples/openclaw-memory-plugin/memory-ranking.ts",
+ "examples/openclaw-memory-plugin/text-utils.ts",
"examples/openclaw-memory-plugin/openclaw.plugin.json",
"examples/openclaw-memory-plugin/package.json",
"examples/openclaw-memory-plugin/package-lock.json",
@@ -325,17 +389,25 @@ function Configure-OpenClawPlugin {
$cfg["plugins"]["allow"] = @("memory-openviking")
$cfg["plugins"]["slots"]["memory"] = "memory-openviking"
$cfg["plugins"]["load"]["paths"] = $mergedPaths
- $ovConfPath = Join-Path $OpenVikingDir "ov.conf"
- $cfg["plugins"]["entries"]["memory-openviking"] = @{
- config = @{
- mode = "local"
- configPath = $ovConfPath
- port = $ServerPort
- targetUri = "viking://user/memories"
- autoRecall = $true
- autoCapture = $true
- }
+
+ $pluginConfig = @{
+ mode = $SelectedMode
+ targetUri = "viking://user/memories"
+ autoRecall = $true
+ autoCapture = $true
}
+
+ if ($SelectedMode -eq "local") {
+ $ovConfPath = Join-Path $OpenVikingDir "ov.conf"
+ $pluginConfig["configPath"] = $ovConfPath
+ $pluginConfig["port"] = $ServerPort
+ } else {
+ $pluginConfig["baseUrl"] = $RemoteBaseUrl
+ if ($RemoteApiKey) { $pluginConfig["apiKey"] = $RemoteApiKey }
+ if ($RemoteAgentId) { $pluginConfig["agentId"] = $RemoteAgentId }
+ }
+
+ $cfg["plugins"]["entries"]["memory-openviking"] = @{ config = $pluginConfig }
$cfg["gateway"]["mode"] = "local"
$cfgJson = $cfg | ConvertTo-Json -Depth 20
@@ -363,24 +435,51 @@ function Write-OpenVikingEnv {
Title (T "🦣 OpenClaw + OpenViking Installer" "🦣 OpenClaw + OpenViking 一键安装")
Write-Host ""
-Validate-Environment
-Check-OpenClaw
-Install-OpenViking
-$serverPort = Configure-OvConf
+Select-Workdir
+Info ("{0} $OpenClawDir" -f (T "Target:" "目标实例:"))
+
+Select-Mode
+Info ("{0} $SelectedMode" -f (T "Mode:" "模式:"))
+
+$serverPort = $DefaultServerPort
+if ($SelectedMode -eq "local") {
+ Validate-Environment
+ Check-OpenClaw
+ Install-OpenViking
+ $serverPort = Configure-OvConf
+} else {
+ Check-OpenClaw
+ Collect-RemoteConfig
+}
+
Download-Plugin
Configure-OpenClawPlugin -ServerPort $serverPort
-Write-OpenVikingEnv
+
+if ($SelectedMode -eq "local") {
+ Write-OpenVikingEnv
+}
Write-Host ""
Title "═══════════════════════════════════════════════════════════"
Title (" {0}" -f (T "Installation complete!" "安装完成!"))
Title "═══════════════════════════════════════════════════════════"
Write-Host ""
-Info (T "Run these commands to start OpenClaw + OpenViking:" "请按以下命令启动 OpenClaw + OpenViking:")
-Write-Host " 1) openclaw --version"
-Write-Host " 2) openclaw onboard"
-Write-Host " 3) . `"$OpenClawDir\openviking.env.ps1`"; openclaw gateway"
-Write-Host " 4) openclaw status"
-Write-Host ""
-Info ("{0} $OpenVikingDir\ov.conf" -f (T "You can edit the config freely:" "你可以按需自由修改配置文件:"))
+
+if ($SelectedMode -eq "local") {
+ Info (T "Run these commands to start OpenClaw + OpenViking:" "请按以下命令启动 OpenClaw + OpenViking:")
+ Write-Host " 1) openclaw --version"
+ Write-Host " 2) openclaw onboard"
+ Write-Host " 3) . `"$OpenClawDir\openviking.env.ps1`"; openclaw gateway"
+ Write-Host " 4) openclaw status"
+ Write-Host ""
+ Info ("{0} $OpenVikingDir\ov.conf" -f (T "You can edit the config freely:" "你可以按需自由修改配置文件:"))
+} else {
+ Info (T "Run these commands to start OpenClaw:" "请按以下命令启动 OpenClaw:")
+ Write-Host " 1) openclaw --version"
+ Write-Host " 2) openclaw onboard"
+ Write-Host " 3) openclaw gateway"
+ Write-Host " 4) openclaw status"
+ Write-Host ""
+ Info ("{0} $RemoteBaseUrl" -f (T "Remote server:" "远程服务器:"))
+}
Write-Host ""
diff --git a/examples/openclaw-memory-plugin/install.sh b/examples/openclaw-memory-plugin/install.sh
index f7a665e89..714d1e336 100644
--- a/examples/openclaw-memory-plugin/install.sh
+++ b/examples/openclaw-memory-plugin/install.sh
@@ -42,19 +42,29 @@ DEFAULT_AGFS_PORT=1833
DEFAULT_VLM_MODEL="doubao-seed-2-0-pro-260215"
DEFAULT_EMBED_MODEL="doubao-embedding-vision-251215"
SELECTED_SERVER_PORT="${DEFAULT_SERVER_PORT}"
+SELECTED_MODE="local"
LANG_UI="en"
# Parse args (supports curl | bash -s -- ...)
+_expect_workdir=""
for arg in "$@"; do
+ if [[ -n "$_expect_workdir" ]]; then
+ OPENCLAW_DIR="$arg"
+ PLUGIN_DEST="${OPENCLAW_DIR}/extensions/memory-openviking"
+ _expect_workdir=""
+ continue
+ fi
[[ "$arg" == "-y" || "$arg" == "--yes" ]] && INSTALL_YES="1"
[[ "$arg" == "--zh" ]] && LANG_UI="zh"
+ [[ "$arg" == "--workdir" ]] && { _expect_workdir="1"; continue; }
[[ "$arg" == "-h" || "$arg" == "--help" ]] && {
- echo "Usage: curl -fsSL <INSTALL_URL> | bash [-s -- -y --zh]"
+ echo "Usage: curl -fsSL <INSTALL_URL> | bash [-s -- -y --zh --workdir <path>]"
echo ""
echo "Options:"
- echo " -y, --yes Non-interactive mode"
- echo " --zh Chinese prompts"
- echo " -h, --help Show this help"
+ echo " -y, --yes Non-interactive mode"
+ echo " --zh Chinese prompts"
+ echo " --workdir <path> OpenClaw config directory (default: ~/.openclaw)"
+ echo " -h, --help Show this help"
echo ""
echo "Env vars: REPO, BRANCH, OPENVIKING_INSTALL_YES, SKIP_OPENCLAW, SKIP_OPENVIKING, NPM_REGISTRY, PIP_INDEX_URL"
exit 0
@@ -125,6 +135,85 @@ detect_distro() {
fi
}
+# ─── Workdir detection & mode selection ───
+
+detect_openclaw_instances() {
+ local instances=()
+ for dir in "${HOME_DIR}"/.openclaw*; do
+ [[ -d "$dir" ]] || continue
+ # skip workspace/data subdirectories
+ [[ "$(basename "$dir")" == .openclaw-* ]] || [[ "$(basename "$dir")" == ".openclaw" ]] || continue
+ instances+=("$dir")
+ done
+ echo "${instances[@]}"
+}
+
+select_workdir() {
+ # Already set via --workdir
+ [[ -n "$OPENCLAW_DIR" && "$OPENCLAW_DIR" != "${HOME_DIR}/.openclaw" ]] && return 0
+
+ local instances=($(detect_openclaw_instances))
+
+ # Only default instance or none — keep default
+ if [[ ${#instances[@]} -le 1 ]]; then
+ return 0
+ fi
+
+ # Multiple instances found — let user pick
+ if [[ "$INSTALL_YES" != "1" ]]; then
+ echo ""
+ bold "$(tr "Found multiple OpenClaw instances:" "发现多个 OpenClaw 实例:")"
+ local i=1
+ for inst in "${instances[@]}"; do
+ echo " ${i}) ${inst}"
+ i=$((i + 1))
+ done
+ echo ""
+ read -r -p "$(tr "Select instance number [1]: " "选择实例编号 [1]: ")" _choice < /dev/tty || true
+ if [[ -n "$_choice" && "$_choice" =~ ^[0-9]+$ ]]; then
+ local idx=$((_choice - 1))
+ if [[ $idx -ge 0 && $idx -lt ${#instances[@]} ]]; then
+ OPENCLAW_DIR="${instances[$idx]}"
+ else
+ warn "$(tr "Invalid selection, using default" "无效选择,使用默认")"
+ OPENCLAW_DIR="${instances[0]}"
+ fi
+ else
+ OPENCLAW_DIR="${instances[0]}"
+ fi
+ PLUGIN_DEST="${OPENCLAW_DIR}/extensions/memory-openviking"
+ fi
+}
+
+select_mode() {
+ if [[ "$INSTALL_YES" == "1" ]]; then
+ SELECTED_MODE="local"
+ return 0
+ fi
+ echo ""
+ read -r -p "$(tr "Plugin mode - local or remote [local]: " "插件模式 - local 或 remote [local]: ")" _mode < /dev/tty || true
+ _mode="${_mode:-local}"
+ if [[ "$_mode" == "remote" ]]; then
+ SELECTED_MODE="remote"
+ else
+ SELECTED_MODE="local"
+ fi
+}
+
+collect_remote_config() {
+ remote_base_url="http://127.0.0.1:1933"
+ remote_api_key=""
+ remote_agent_id=""
+ if [[ "$INSTALL_YES" != "1" ]]; then
+ read -r -p "$(tr "OpenViking server URL [${remote_base_url}]: " "OpenViking 服务器地址 [${remote_base_url}]: ")" _base_url < /dev/tty || true
+ read -r -p "$(tr "API Key (optional): " "API Key(可选): ")" _api_key < /dev/tty || true
+ read -r -p "$(tr "Agent ID (optional): " "Agent ID(可选): ")" _agent_id < /dev/tty || true
+ remote_base_url="${_base_url:-$remote_base_url}"
+ remote_api_key="${_api_key:-}"
+ remote_agent_id="${_agent_id:-}"
+ fi
+}
+
# ─── Environment checks ───
check_python() {
@@ -465,6 +554,10 @@ download_plugin() {
local files=(
"examples/openclaw-memory-plugin/index.ts"
"examples/openclaw-memory-plugin/config.ts"
+ "examples/openclaw-memory-plugin/client.ts"
+ "examples/openclaw-memory-plugin/process-manager.ts"
+ "examples/openclaw-memory-plugin/memory-ranking.ts"
+ "examples/openclaw-memory-plugin/text-utils.ts"
"examples/openclaw-memory-plugin/openclaw.plugin.json"
"examples/openclaw-memory-plugin/package.json"
"examples/openclaw-memory-plugin/package-lock.json"
@@ -511,22 +604,37 @@ download_plugin() {
}
configure_openclaw_plugin() {
- local server_port="${SELECTED_SERVER_PORT}"
- # Use absolute path so openclaw works when started from any cwd (e.g. root from /root)
- local config_path="${OPENVIKING_DIR}/ov.conf"
info "$(tr "Configuring OpenClaw plugin..." "正在配置 OpenClaw 插件...")"
- openclaw config set plugins.enabled true
- openclaw config set plugins.allow '["memory-openviking"]' --json
- openclaw config set gateway.mode local
- openclaw config set plugins.slots.memory memory-openviking
- openclaw config set plugins.load.paths "[\"${PLUGIN_DEST}\"]" --json
- openclaw config set plugins.entries.memory-openviking.config.mode local
- openclaw config set plugins.entries.memory-openviking.config.configPath "${config_path}"
- openclaw config set plugins.entries.memory-openviking.config.port "${server_port}"
- openclaw config set plugins.entries.memory-openviking.config.targetUri viking://user/memories
- openclaw config set plugins.entries.memory-openviking.config.autoRecall true --json
- openclaw config set plugins.entries.memory-openviking.config.autoCapture true --json
+ local oc_env=()
+ if [[ "$OPENCLAW_DIR" != "${HOME_DIR}/.openclaw" ]]; then
+ oc_env=(env OPENCLAW_STATE_DIR="$OPENCLAW_DIR")
+ fi
+
+ "${oc_env[@]}" openclaw config set plugins.enabled true
+ "${oc_env[@]}" openclaw config set plugins.allow '["memory-openviking"]' --json
+ "${oc_env[@]}" openclaw config set gateway.mode local
+ "${oc_env[@]}" openclaw config set plugins.slots.memory memory-openviking
+ "${oc_env[@]}" openclaw config set plugins.load.paths "[\"${PLUGIN_DEST}\"]" --json
+ "${oc_env[@]}" openclaw config set plugins.entries.memory-openviking.config.mode "${SELECTED_MODE}"
+ "${oc_env[@]}" openclaw config set plugins.entries.memory-openviking.config.targetUri viking://user/memories
+ "${oc_env[@]}" openclaw config set plugins.entries.memory-openviking.config.autoRecall true --json
+ "${oc_env[@]}" openclaw config set plugins.entries.memory-openviking.config.autoCapture true --json
+
+ if [[ "$SELECTED_MODE" == "local" ]]; then
+ local config_path="${OPENVIKING_DIR}/ov.conf"
+ "${oc_env[@]}" openclaw config set plugins.entries.memory-openviking.config.configPath "${config_path}"
+ "${oc_env[@]}" openclaw config set plugins.entries.memory-openviking.config.port "${SELECTED_SERVER_PORT}"
+ else
+ "${oc_env[@]}" openclaw config set plugins.entries.memory-openviking.config.baseUrl "${remote_base_url}"
+ if [[ -n "${remote_api_key}" ]]; then
+ "${oc_env[@]}" openclaw config set plugins.entries.memory-openviking.config.apiKey "${remote_api_key}"
+ fi
+ if [[ -n "${remote_agent_id}" ]]; then
+ "${oc_env[@]}" openclaw config set plugins.entries.memory-openviking.config.agentId "${remote_agent_id}"
+ fi
+ fi
+
info "$(tr "OpenClaw plugin configured" "OpenClaw 插件配置完成")"
}
@@ -552,27 +660,51 @@ main() {
echo ""
detect_os
- validate_environment
+ select_workdir
+ info "$(tr "Target: ${OPENCLAW_DIR}" "目标实例: ${OPENCLAW_DIR}")"
+
+ select_mode
+ info "$(tr "Mode: ${SELECTED_MODE}" "模式: ${SELECTED_MODE}")"
+
+ if [[ "$SELECTED_MODE" == "local" ]]; then
+ validate_environment
+ install_openclaw
+ install_openviking
+ configure_openviking_conf
+ else
+ install_openclaw
+ collect_remote_config
+ fi
- install_openclaw
- install_openviking
- configure_openviking_conf
download_plugin
configure_openclaw_plugin
- write_openviking_env
+
+ if [[ "$SELECTED_MODE" == "local" ]]; then
+ write_openviking_env
+ fi
echo ""
bold "═══════════════════════════════════════════════════════════"
bold " $(tr "Installation complete!" "安装完成!")"
bold "═══════════════════════════════════════════════════════════"
echo ""
- info "$(tr "Run these commands to start OpenClaw + OpenViking:" "请按以下命令启动 OpenClaw + OpenViking:")"
- echo " 1) openclaw --version"
- echo " 2) openclaw onboard"
- echo " 3) source ${OPENCLAW_DIR}/openviking.env && openclaw gateway"
- echo " 4) openclaw status"
- echo ""
- info "$(tr "You can edit the config freely: ${OPENVIKING_DIR}/ov.conf" "你可以按需自由修改配置文件: ${OPENVIKING_DIR}/ov.conf")"
+ if [[ "$SELECTED_MODE" == "local" ]]; then
+ info "$(tr "Run these commands to start OpenClaw + OpenViking:" "请按以下命令启动 OpenClaw + OpenViking:")"
+ echo " 1) openclaw --version"
+ echo " 2) openclaw onboard"
+ echo " 3) source ${OPENCLAW_DIR}/openviking.env && openclaw gateway"
+ echo " 4) openclaw status"
+ echo ""
+ info "$(tr "You can edit the config freely: ${OPENVIKING_DIR}/ov.conf" "你可以按需自由修改配置文件: ${OPENVIKING_DIR}/ov.conf")"
+ else
+ info "$(tr "Run these commands to start OpenClaw:" "请按以下命令启动 OpenClaw:")"
+ echo " 1) openclaw --version"
+ echo " 2) openclaw onboard"
+ echo " 3) openclaw gateway"
+ echo " 4) openclaw status"
+ echo ""
+ info "$(tr "Remote server: ${remote_base_url}" "远程服务器: ${remote_base_url}")"
+ fi
echo ""
}
diff --git a/examples/openclaw-memory-plugin/memory-ranking.ts b/examples/openclaw-memory-plugin/memory-ranking.ts
new file mode 100644
index 000000000..4b1530992
--- /dev/null
+++ b/examples/openclaw-memory-plugin/memory-ranking.ts
@@ -0,0 +1,260 @@
+import type { FindResultItem } from "./client.js";
+
+export function clampScore(value: number | undefined): number {
+ if (typeof value !== "number" || Number.isNaN(value)) {
+ return 0;
+ }
+ return Math.max(0, Math.min(1, value));
+}
+
+function normalizeDedupeText(text: string): string {
+ return text.toLowerCase().replace(/\s+/g, " ").trim();
+}
+
+function isEventOrCaseMemory(item: FindResultItem): boolean {
+ const category = (item.category ?? "").toLowerCase();
+ const uri = item.uri.toLowerCase();
+ return (
+ category === "events" ||
+ category === "cases" ||
+ uri.includes("/events/") ||
+ uri.includes("/cases/")
+ );
+}
+
+function getMemoryDedupeKey(item: FindResultItem): string {
+ const abstract = normalizeDedupeText(item.abstract ?? item.overview ?? "");
+ const category = (item.category ?? "").toLowerCase() || "unknown";
+ if (abstract && !isEventOrCaseMemory(item)) {
+ return `abstract:${category}:${abstract}`;
+ }
+ return `uri:${item.uri}`;
+}
+
+export function postProcessMemories(
+ items: FindResultItem[],
+ options: {
+ limit: number;
+ scoreThreshold: number;
+ leafOnly?: boolean;
+ },
+): FindResultItem[] {
+ const deduped: FindResultItem[] = [];
+ const seen = new Set<string>();
+ const sorted = [...items].sort((a, b) => clampScore(b.score) - clampScore(a.score));
+ for (const item of sorted) {
+ if (options.leafOnly && item.level !== 2) {
+ continue;
+ }
+ if (clampScore(item.score) < options.scoreThreshold) {
+ continue;
+ }
+ const key = getMemoryDedupeKey(item);
+ if (seen.has(key)) {
+ continue;
+ }
+ seen.add(key);
+ deduped.push(item);
+ if (deduped.length >= options.limit) {
+ break;
+ }
+ }
+ return deduped;
+}
+
+export function formatMemoryLines(items: FindResultItem[]): string {
+ return items
+ .map((item, index) => {
+ const score = clampScore(item.score);
+ const abstract = item.abstract?.trim() || item.overview?.trim() || item.uri;
+ const category = item.category ?? "memory";
+ return `${index + 1}. [${category}] ${abstract} (${(score * 100).toFixed(0)}%)`;
+ })
+ .join("\n");
+}
+
+export function trimForLog(value: string, limit = 260): string {
+ const normalized = value.trim();
+ if (normalized.length <= limit) {
+ return normalized;
+ }
+ return `${normalized.slice(0, limit)}...`;
+}
+
+export function toJsonLog(value: unknown, maxLen = 6000): string {
+ try {
+ const json = JSON.stringify(value);
+ if (json.length <= maxLen) {
+ return json;
+ }
+ return JSON.stringify({
+ truncated: true,
+ length: json.length,
+ preview: `${json.slice(0, maxLen)}...`,
+ });
+ } catch {
+ return JSON.stringify({ error: "stringify_failed" });
+ }
+}
+
+export function summarizeInjectionMemories(items: FindResultItem[]): Array<Record<string, unknown>> {
+ return items.map((item) => ({
+ uri: item.uri,
+ category: item.category ?? null,
+ abstract: trimForLog(item.abstract?.trim() || item.overview?.trim() || item.uri, 180),
+ score: clampScore(item.score),
+ is_leaf: item.level === 2,
+ }));
+}
+
+export function summarizeExtractedMemories(
+ items: Array<Record<string, unknown>>,
+): Array<Record<string, unknown>> {
+ return items.slice(0, 10).map((item) => {
+ const abstractRaw =
+ typeof item.abstract === "string"
+ ? item.abstract
+ : typeof item.overview === "string"
+ ? item.overview
+ : typeof item.title === "string"
+ ? item.title
+ : "";
+ return {
+ uri: typeof item.uri === "string" ? item.uri : null,
+ category: typeof item.category === "string" ? item.category : null,
+ abstract: trimForLog(abstractRaw, 180),
+ is_leaf: item.level === 2,
+ };
+ });
+}
+
+function isPreferencesMemory(item: FindResultItem): boolean {
+ return (
+ item.category === "preferences" ||
+ item.uri.includes("/preferences/") ||
+ item.uri.endsWith("/preferences")
+ );
+}
+
+function isEventMemory(item: FindResultItem): boolean {
+ const category = (item.category ?? "").toLowerCase();
+ return category === "events" || item.uri.includes("/events/");
+}
+
+function isLeafLikeMemory(item: FindResultItem): boolean {
+ return item.level === 2 || item.uri.endsWith(".md");
+}
+
+const PREFERENCE_QUERY_RE = /prefer|preference|favorite|favourite|like|偏好|喜欢|爱好|更倾向/i;
+const TEMPORAL_QUERY_RE =
+ /when|what time|date|day|month|year|yesterday|today|tomorrow|last|next|什么时候|何时|哪天|几月|几年|昨天|今天|明天|上周|下周|上个月|下个月|去年|明年/i;
+const QUERY_TOKEN_RE = /[a-z0-9]{2,}/gi;
+const QUERY_TOKEN_STOPWORDS = new Set([
+ "what",
+ "when",
+ "where",
+ "which",
+ "who",
+ "whom",
+ "whose",
+ "why",
+ "how",
+ "did",
+ "does",
+ "is",
+ "are",
+ "was",
+ "were",
+ "the",
+ "and",
+ "for",
+ "with",
+ "from",
+ "that",
+ "this",
+ "your",
+ "you",
+]);
+
+type RecallQueryProfile = {
+ tokens: string[];
+ wantsPreference: boolean;
+ wantsTemporal: boolean;
+};
+
+function buildRecallQueryProfile(query: string): RecallQueryProfile {
+ const text = query.trim();
+ const allTokens = text.toLowerCase().match(QUERY_TOKEN_RE) ?? [];
+ const tokens = allTokens.filter((token) => !QUERY_TOKEN_STOPWORDS.has(token));
+ return {
+ tokens,
+ wantsPreference: PREFERENCE_QUERY_RE.test(text),
+ wantsTemporal: TEMPORAL_QUERY_RE.test(text),
+ };
+}
+
+function lexicalOverlapBoost(tokens: string[], text: string): number {
+ if (tokens.length === 0 || !text) {
+ return 0;
+ }
+ const haystack = ` ${text.toLowerCase()} `;
+ let matched = 0;
+ for (const token of tokens.slice(0, 8)) {
+ if (haystack.includes(` ${token} `) || haystack.includes(token)) {
+ matched += 1;
+ }
+ }
+ return Math.min(0.2, (matched / Math.min(tokens.length, 4)) * 0.2);
+}
+
+function rankForInjection(item: FindResultItem, query: RecallQueryProfile): number {
+ // Keep ranking simple and stable: semantic score + light query-aware boosts.
+ const baseScore = clampScore(item.score);
+ const abstract = (item.abstract ?? item.overview ?? "").trim();
+ const leafBoost = isLeafLikeMemory(item) ? 0.12 : 0;
+ const eventBoost = query.wantsTemporal && isEventMemory(item) ? 0.1 : 0;
+ const preferenceBoost = query.wantsPreference && isPreferencesMemory(item) ? 0.08 : 0;
+ const overlapBoost = lexicalOverlapBoost(query.tokens, `${item.uri} ${abstract}`);
+ return baseScore + leafBoost + eventBoost + preferenceBoost + overlapBoost;
+}
+
+export function pickMemoriesForInjection(
+ items: FindResultItem[],
+ limit: number,
+ queryText: string,
+): FindResultItem[] {
+ if (items.length === 0 || limit <= 0) {
+ return [];
+ }
+
+ const query = buildRecallQueryProfile(queryText);
+ const sorted = [...items].sort((a, b) => rankForInjection(b, query) - rankForInjection(a, query));
+ const deduped: FindResultItem[] = [];
+ const seen = new Set<string>();
+ for (const item of sorted) {
+ const abstractKey = (item.abstract ?? item.overview ?? "").trim().toLowerCase();
+ const key = abstractKey || item.uri;
+ if (seen.has(key)) {
+ continue;
+ }
+ seen.add(key);
+ deduped.push(item);
+ }
+ const leaves = deduped.filter((item) => isLeafLikeMemory(item));
+ if (leaves.length >= limit) {
+ return leaves.slice(0, limit);
+ }
+
+ const picked = [...leaves];
+ const used = new Set(leaves.map((item) => item.uri));
+ for (const item of deduped) {
+ if (picked.length >= limit) {
+ break;
+ }
+ if (used.has(item.uri)) {
+ continue;
+ }
+ picked.push(item);
+ }
+ return picked;
+}
diff --git a/examples/openclaw-memory-plugin/openclaw.plugin.json b/examples/openclaw-memory-plugin/openclaw.plugin.json
index 9874273cb..a70096c1a 100644
--- a/examples/openclaw-memory-plugin/openclaw.plugin.json
+++ b/examples/openclaw-memory-plugin/openclaw.plugin.json
@@ -22,6 +22,11 @@
"placeholder": "http://127.0.0.1:1933",
"help": "HTTP URL when mode is remote (or ${OPENVIKING_BASE_URL})"
},
+ "agentId": {
+ "label": "Agent ID",
+ "placeholder": "random unique ID",
+ "help": "Identifies this agent to OpenViking. A random unique ID is generated if not set."
+ },
"apiKey": {
"label": "OpenViking API Key",
"sensitive": true,
@@ -60,7 +65,7 @@
},
"recallLimit": {
"label": "Recall Limit",
- "placeholder": "6",
+ "placeholder": "20",
"advanced": true
},
"recallScoreThreshold": {
@@ -102,6 +107,9 @@
"baseUrl": {
"type": "string"
},
+ "agentId": {
+ "type": "string"
+ },
"apiKey": {
"type": "string"
},
diff --git a/examples/openclaw-memory-plugin/package-lock.json b/examples/openclaw-memory-plugin/package-lock.json
index 71a8e81bb..01bb6870c 100644
--- a/examples/openclaw-memory-plugin/package-lock.json
+++ b/examples/openclaw-memory-plugin/package-lock.json
@@ -9,6 +9,9 @@
"version": "2026.2.6-3",
"dependencies": {
"@sinclair/typebox": "0.34.48"
+ },
+ "devDependencies": {
+ "@types/node": "^25.3.5"
}
},
"node_modules/@sinclair/typebox": {
@@ -16,6 +19,23 @@
"resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.34.48.tgz",
"integrity": "sha512-kKJTNuK3AQOrgjjotVxMrCn1sUJwM76wMszfq1kdU4uYVJjvEWuFQ6HgvLt4Xz3fSmZlTOxJ/Ie13KnIcWQXFA==",
"license": "MIT"
+ },
+ "node_modules/@types/node": {
+ "version": "25.3.5",
+ "resolved": "https://registry.npmmirror.com/@types/node/-/node-25.3.5.tgz",
+ "integrity": "sha512-oX8xrhvpiyRCQkG1MFchB09f+cXftgIXb3a7UUa4Y3wpmZPw5tyZGTLWhlESOLq1Rq6oDlc8npVU2/9xiCuXMA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": "~7.18.0"
+ }
+ },
+ "node_modules/undici-types": {
+ "version": "7.18.2",
+ "resolved": "https://registry.npmmirror.com/undici-types/-/undici-types-7.18.2.tgz",
+ "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==",
+ "dev": true,
+ "license": "MIT"
}
}
}
diff --git a/examples/openclaw-memory-plugin/package.json b/examples/openclaw-memory-plugin/package.json
index 5900ecaa5..790ae6bce 100644
--- a/examples/openclaw-memory-plugin/package.json
+++ b/examples/openclaw-memory-plugin/package.json
@@ -7,6 +7,11 @@
"@sinclair/typebox": "0.34.48"
},
"openclaw": {
- "extensions": ["./index.ts"]
+ "extensions": [
+ "./index.ts"
+ ]
+ },
+ "devDependencies": {
+ "@types/node": "^25.3.5"
}
}
diff --git a/examples/openclaw-memory-plugin/process-manager.ts b/examples/openclaw-memory-plugin/process-manager.ts
new file mode 100644
index 000000000..6a006103d
--- /dev/null
+++ b/examples/openclaw-memory-plugin/process-manager.ts
@@ -0,0 +1,196 @@
+import { execSync } from "node:child_process";
+import { readFileSync, existsSync } from "node:fs";
+import { Socket } from "node:net";
+import { platform } from "node:os";
+import type { spawn } from "node:child_process";
+
+export const IS_WIN = platform() === "win32";
+
+export function waitForHealth(baseUrl: string, timeoutMs: number, intervalMs: number): Promise<void> {
+ const deadline = Date.now() + timeoutMs;
+ return new Promise((resolve, reject) => {
+ const tick = () => {
+ if (Date.now() > deadline) {
+ reject(new Error(`OpenViking health check timeout at ${baseUrl}`));
+ return;
+ }
+ fetch(`${baseUrl}/health`)
+ .then((r) => r.json())
+ .then((body: { status?: string }) => {
+ if (body?.status === "ok") {
+ resolve();
+ return;
+ }
+ setTimeout(tick, intervalMs);
+ })
+ .catch(() => setTimeout(tick, intervalMs));
+ };
+ tick();
+ });
+}
+
+export function withTimeout<T>(promise: Promise<T>, timeoutMs: number, timeoutMessage: string): Promise<T> {
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error(timeoutMessage)), timeoutMs);
+ promise.then(
+ (value) => {
+ clearTimeout(timer);
+ resolve(value);
+ },
+ (err) => {
+ clearTimeout(timer);
+ reject(err);
+ },
+ );
+ });
+}
+
+export function quickTcpProbe(host: string, port: number, timeoutMs: number): Promise<boolean> {
+ return new Promise((resolve) => {
+ const socket = new Socket();
+ let done = false;
+ const finish = (ok: boolean) => {
+ if (done) {
+ return;
+ }
+ done = true;
+ socket.destroy();
+ resolve(ok);
+ };
+ socket.setTimeout(timeoutMs);
+ socket.once("connect", () => finish(true));
+ socket.once("timeout", () => finish(false));
+ socket.once("error", () => finish(false));
+ try {
+ socket.connect(port, host);
+ } catch {
+ finish(false);
+ }
+ });
+}
+
+export async function quickHealthCheck(baseUrl: string, timeoutMs: number): Promise<boolean> {
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
+ try {
+ const response = await fetch(`${baseUrl}/health`, {
+ method: "GET",
+ signal: controller.signal,
+ });
+ if (!response.ok) {
+ return false;
+ }
+ const body = (await response.json().catch(() => ({}))) as { status?: string };
+ return body.status === "ok";
+ } catch {
+ return false;
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+export async function quickRecallPrecheck(
+ mode: "local" | "remote",
+ baseUrl: string,
+ defaultPort: number,
+ localProcess: ReturnType<typeof spawn> | null,
+): Promise<{ ok: true } | { ok: false; reason: string }> {
+ const healthOk = await quickHealthCheck(baseUrl, 500);
+ if (healthOk) {
+ return { ok: true };
+ }
+
+ let host = "127.0.0.1";
+ let port = defaultPort;
+ try {
+ const parsed = new URL(baseUrl);
+ if (parsed.hostname) {
+ host = parsed.hostname;
+ }
+ if (parsed.port) {
+ const parsedPort = Number(parsed.port);
+ if (Number.isFinite(parsedPort) && parsedPort > 0) {
+ port = parsedPort;
+ }
+ }
+ } catch {
+ // Keep defaults when baseUrl is malformed.
+ }
+
+ if (mode === "local") {
+ const portOk = await quickTcpProbe(host, port, 200);
+ if (!portOk) {
+ return { ok: false, reason: `local port unavailable (${host}:${port})` };
+ }
+ if (localProcess && (localProcess.killed || localProcess.exitCode !== null || localProcess.signalCode !== null)) {
+ return { ok: false, reason: "local process is not running" };
+ }
+ }
+ return { ok: false, reason: "health check failed" };
+}
+
+export interface ProcessLogger {
+ info?: (msg: string) => void;
+}
+
+export function resolvePythonCommand(logger: ProcessLogger): string {
+ const defaultPy = IS_WIN ? "python" : "python3";
+ let pythonCmd = process.env.OPENVIKING_PYTHON;
+
+ if (!pythonCmd) {
+ if (IS_WIN) {
+ const { join } = require("node:path") as typeof import("node:path");
+ const { homedir } = require("node:os") as typeof import("node:os");
+ const envBat = join(homedir(), ".openclaw", "openviking.env.bat");
+ if (existsSync(envBat)) {
+ try {
+ const content = readFileSync(envBat, "utf-8");
+ const m = content.match(/set\s+OPENVIKING_PYTHON=(.+)/i);
+ if (m?.[1]) pythonCmd = m[1].trim();
+ } catch { /* ignore */ }
+ }
+ } else {
+ const { join } = require("node:path") as typeof import("node:path");
+ const { homedir } = require("node:os") as typeof import("node:os");
+ const envFile = join(homedir(), ".openclaw", "openviking.env");
+ if (existsSync(envFile)) {
+ try {
+ const content = readFileSync(envFile, "utf-8");
+ const m = content.match(/OPENVIKING_PYTHON=['"]([^'"]+)['"]/);
+ if (m?.[1]) pythonCmd = m[1];
+ } catch {
+ /* ignore */
+ }
+ }
+ }
+ }
+
+ if (!pythonCmd) {
+ if (IS_WIN) {
+ try {
+ pythonCmd = execSync("where python", { encoding: "utf-8", shell: true }).split(/\r?\n/)[0].trim();
+ } catch {
+ pythonCmd = "python";
+ }
+ } else {
+ try {
+ pythonCmd = execSync("command -v python3 || which python3", {
+ encoding: "utf-8",
+ env: process.env,
+ shell: "/bin/sh",
+ }).trim();
+ } catch {
+ pythonCmd = "python3";
+ }
+ }
+ }
+
+ if (pythonCmd === defaultPy) {
+ logger.info?.(
+ `memory-openviking: 未解析到 ${defaultPy} 路径,将用 "${defaultPy}"。若 openviking 在自定义 Python 下,请设置 OPENVIKING_PYTHON` +
+ (IS_WIN ? ' 或 call "%USERPROFILE%\\.openclaw\\openviking.env.bat"' : " 或 source ~/.openclaw/openviking.env"),
+ );
+ }
+
+ return pythonCmd;
+}
diff --git a/examples/openclaw-memory-plugin/setup-helper/cli.js b/examples/openclaw-memory-plugin/setup-helper/cli.js
index 41757a40e..3aa95b99a 100755
--- a/examples/openclaw-memory-plugin/setup-helper/cli.js
+++ b/examples/openclaw-memory-plugin/setup-helper/cli.js
@@ -10,7 +10,7 @@ import { mkdir, writeFile, access, readFile, rm } from "node:fs/promises";
import { createInterface } from "node:readline";
import { join, dirname } from "node:path";
import { fileURLToPath } from "node:url";
-import { existsSync } from "node:fs";
+import { existsSync, readdirSync } from "node:fs";
const __dirname = dirname(fileURLToPath(import.meta.url));
const GITHUB_RAW =
@@ -20,10 +20,10 @@ const GITHUB_RAW =
const IS_WIN = process.platform === "win32";
const IS_LINUX = process.platform === "linux";
const HOME = process.env.HOME || process.env.USERPROFILE || "";
-const OPENCLAW_DIR = join(HOME, ".openclaw");
+let OPENCLAW_DIR = join(HOME, ".openclaw");
const OPENVIKING_DIR = join(HOME, ".openviking");
-const EXT_DIR = join(OPENCLAW_DIR, "extensions");
-const PLUGIN_DEST = join(EXT_DIR, "memory-openviking");
+let EXT_DIR = join(OPENCLAW_DIR, "extensions");
+let PLUGIN_DEST = join(EXT_DIR, "memory-openviking");
// ─── Utility helpers ───
@@ -102,6 +102,60 @@ async function questionApiKey(prompt) {
});
}
+// ─── Workdir detection & mode selection ───
+
+function detectOpenclawInstances() {
+ const instances = [];
+ try {
+ const entries = readdirSync(HOME, { withFileTypes: true });
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue;
+ if (entry.name === ".openclaw" || entry.name.startsWith(".openclaw-")) {
+ instances.push(join(HOME, entry.name));
+ }
+ }
+ } catch {}
+ return instances.sort();
+}
+
+async function selectWorkdir(nonInteractive) {
+ const instances = detectOpenclawInstances();
+ if (instances.length <= 1) return; // keep default
+
+ if (nonInteractive) return;
+
+ console.log("\nFound multiple OpenClaw instances:");
+ for (let i = 0; i < instances.length; i++) {
+ console.log(` ${i + 1}) ${instances[i]}`);
+ }
+ const choice = await question("Select instance number", "1");
+ const idx = parseInt(choice, 10) - 1;
+ if (idx >= 0 && idx < instances.length) {
+ OPENCLAW_DIR = instances[idx];
+ } else {
+ log("Invalid selection, using default", "warn");
+ OPENCLAW_DIR = instances[0];
+ }
+ EXT_DIR = join(OPENCLAW_DIR, "extensions");
+ PLUGIN_DEST = join(EXT_DIR, "memory-openviking");
+}
+
+async function selectMode(nonInteractive) {
+ if (nonInteractive) return "local";
+ const choice = await question("Plugin mode (local/remote)", "local");
+ return choice.toLowerCase() === "remote" ? "remote" : "local";
+}
+
+async function collectRemoteConfig(nonInteractive) {
+ const opts = { baseUrl: "http://127.0.0.1:1933", apiKey: "", agentId: "" };
+ if (nonInteractive) return opts;
+
+ opts.baseUrl = await question("OpenViking server URL", opts.baseUrl);
+ opts.apiKey = (await questionApiKey("API Key (optional, leave blank to skip): ")) || "";
+ opts.agentId = (await questionApiKey("Agent ID (optional, leave blank to skip): ")) || "";
+ return opts;
+}
+
// ─── Distro detection ───
async function detectDistro() {
@@ -428,7 +482,7 @@ async function fixStalePluginPaths(pluginPath) {
} catch {}
}
-async function configureOpenclawViaJson(pluginPath, serverPort) {
+async function configureOpenclawViaJson(pluginPath, serverPort, pluginMode = "local", remoteOpts = {}) {
const cfgPath = join(OPENCLAW_DIR, "openclaw.json");
let cfg = {};
try { cfg = JSON.parse(await readFile(cfgPath, "utf8")); } catch { /* start fresh */ }
@@ -442,31 +496,41 @@ async function configureOpenclawViaJson(pluginPath, serverPort) {
if (!paths.includes(pluginPath)) paths.push(pluginPath);
cfg.plugins.load.paths = paths;
if (!cfg.plugins.entries) cfg.plugins.entries = {};
- const ovConfPath = join(OPENVIKING_DIR, "ov.conf");
- cfg.plugins.entries["memory-openviking"] = {
- config: {
- mode: "local",
- configPath: ovConfPath,
- port: serverPort,
- targetUri: "viking://user/memories",
- autoRecall: true,
- autoCapture: true,
- },
+
+ const pluginConfig = {
+ mode: pluginMode,
+ targetUri: "viking://user/memories",
+ autoRecall: true,
+ autoCapture: true,
};
+ if (pluginMode === "local") {
+ pluginConfig.configPath = join(OPENVIKING_DIR, "ov.conf");
+ pluginConfig.port = serverPort;
+ } else {
+ pluginConfig.baseUrl = remoteOpts.baseUrl || "http://127.0.0.1:1933";
+ if (remoteOpts.apiKey) pluginConfig.apiKey = remoteOpts.apiKey;
+ if (remoteOpts.agentId) pluginConfig.agentId = remoteOpts.agentId;
+ }
+ cfg.plugins.entries["memory-openviking"] = { config: pluginConfig };
+
if (!cfg.gateway) cfg.gateway = {};
cfg.gateway.mode = "local";
await mkdir(OPENCLAW_DIR, { recursive: true });
await writeFile(cfgPath, JSON.stringify(cfg, null, 2) + "\n");
}
-async function configureOpenclawViaCli(pluginPath, serverPort, mode) {
- const runNoShell = (cmd, args, opts = {}) => run(cmd, args, { ...opts, shell: false });
- if (mode === "link") {
+async function configureOpenclawViaCli(pluginPath, serverPort, installMode, pluginMode = "local", remoteOpts = {}) {
+ const extraEnv = OPENCLAW_DIR !== join(HOME, ".openclaw")
+ ? { env: { ...process.env, OPENCLAW_STATE_DIR: OPENCLAW_DIR } }
+ : {};
+ const runNoShell = (cmd, args, opts = {}) => run(cmd, args, { ...opts, ...extraEnv, shell: false });
+
+ if (installMode === "link") {
if (existsSync(PLUGIN_DEST)) {
log(`Removing old plugin dir ${PLUGIN_DEST}...`, "info");
await rm(PLUGIN_DEST, { recursive: true, force: true });
}
- await run("openclaw", ["plugins", "install", "-l", pluginPath]);
+ await run("openclaw", ["plugins", "install", "-l", pluginPath], extraEnv);
} else {
await runNoShell("openclaw", ["config", "set", "plugins.load.paths", JSON.stringify([pluginPath])], { silent: true }).catch(() => {});
}
@@ -474,21 +538,32 @@ async function configureOpenclawViaCli(pluginPath, serverPort, mode) {
await runNoShell("openclaw", ["config", "set", "plugins.allow", JSON.stringify(["memory-openviking"]), "--json"]);
await runNoShell("openclaw", ["config", "set", "gateway.mode", "local"]);
await runNoShell("openclaw", ["config", "set", "plugins.slots.memory", "memory-openviking"]);
- await runNoShell("openclaw", ["config", "set", "plugins.entries.memory-openviking.config.mode", "local"]);
- const ovConfPath = join(OPENVIKING_DIR, "ov.conf");
- await runNoShell("openclaw", ["config", "set", "plugins.entries.memory-openviking.config.configPath", ovConfPath]);
- await runNoShell("openclaw", ["config", "set", "plugins.entries.memory-openviking.config.port", String(serverPort)]);
+ await runNoShell("openclaw", ["config", "set", "plugins.entries.memory-openviking.config.mode", pluginMode]);
await runNoShell("openclaw", ["config", "set", "plugins.entries.memory-openviking.config.targetUri", "viking://user/memories"]);
await runNoShell("openclaw", ["config", "set", "plugins.entries.memory-openviking.config.autoRecall", "true", "--json"]);
await runNoShell("openclaw", ["config", "set", "plugins.entries.memory-openviking.config.autoCapture", "true", "--json"]);
+
+ if (pluginMode === "local") {
+ const ovConfPath = join(OPENVIKING_DIR, "ov.conf");
+ await runNoShell("openclaw", ["config", "set", "plugins.entries.memory-openviking.config.configPath", ovConfPath]);
+ await runNoShell("openclaw", ["config", "set", "plugins.entries.memory-openviking.config.port", String(serverPort)]);
+ } else {
+ await runNoShell("openclaw", ["config", "set", "plugins.entries.memory-openviking.config.baseUrl", remoteOpts.baseUrl || "http://127.0.0.1:1933"]);
+ if (remoteOpts.apiKey) {
+ await runNoShell("openclaw", ["config", "set", "plugins.entries.memory-openviking.config.apiKey", remoteOpts.apiKey]);
+ }
+ if (remoteOpts.agentId) {
+ await runNoShell("openclaw", ["config", "set", "plugins.entries.memory-openviking.config.agentId", remoteOpts.agentId]);
+ }
+ }
}
-async function configureOpenclaw(pluginPath, serverPort = DEFAULT_SERVER_PORT, mode = "link") {
+async function configureOpenclaw(pluginPath, serverPort = DEFAULT_SERVER_PORT, installMode = "link", pluginMode = "local", remoteOpts = {}) {
await fixStalePluginPaths(pluginPath);
if (IS_WIN) {
- await configureOpenclawViaJson(pluginPath, serverPort);
+ await configureOpenclawViaJson(pluginPath, serverPort, pluginMode, remoteOpts);
} else {
- await configureOpenclawViaCli(pluginPath, serverPort, mode);
+ await configureOpenclawViaCli(pluginPath, serverPort, installMode, pluginMode, remoteOpts);
}
log("OpenClaw plugin config done", "ok");
}
@@ -535,6 +610,15 @@ async function main() {
const help = args.includes("--help") || args.includes("-h");
const nonInteractive = args.includes("--yes") || args.includes("-y");
+ // Parse --workdir
+ for (let i = 0; i < args.length; i++) {
+ if (args[i] === "--workdir" && i + 1 < args.length) {
+ OPENCLAW_DIR = args[i + 1];
+ EXT_DIR = join(OPENCLAW_DIR, "extensions");
+ PLUGIN_DEST = join(EXT_DIR, "memory-openviking");
+ }
+ }
+
if (help) {
console.log(`
OpenClaw + OpenViking setup helper
@@ -542,8 +626,9 @@ OpenClaw + OpenViking setup helper
Usage: npx openclaw-openviking-setup-helper [options]
Options:
- -y, --yes Non-interactive, use defaults
- -h, --help Show help
+ -y, --yes Non-interactive, use defaults
+ --workdir <path> OpenClaw config directory (default: ~/.openclaw)
+ -h, --help Show help
Steps:
1. Check OpenClaw
@@ -565,8 +650,21 @@ Env vars:
console.log("\n\ud83e\udd9e OpenClaw + OpenViking setup helper\n");
+ // Workdir & mode selection
+ await selectWorkdir(nonInteractive);
+ log(`Target: ${OPENCLAW_DIR}`, "info");
+
+ const pluginMode = await selectMode(nonInteractive);
+ log(`Mode: ${pluginMode}`, "info");
+
+ let remoteOpts = {};
+ if (pluginMode === "remote") {
+ remoteOpts = await collectRemoteConfig(nonInteractive);
+ }
+
const distro = await detectDistro();
+ if (pluginMode === "local") {
// ════════════════════════════════════════════
// Phase 1: Check build tools & runtime environment
// cmake/g++ must be present before OpenClaw install (node-llama-cpp needs them)
@@ -673,6 +771,7 @@ Env vars:
console.log(" npx ./examples/openclaw-memory-plugin/setup-helper\n");
process.exit(1);
}
+ } // end if pluginMode === "local" (Phase 1)
// ════════════════════════════════════════════
// Phase 2: Check OpenClaw
@@ -694,6 +793,15 @@ Env vars:
}
log("OpenClaw: installed", "ok");
+ let ovOpts = {
+ apiKey: process.env.OPENVIKING_ARK_API_KEY || "",
+ serverPort: DEFAULT_SERVER_PORT,
+ agfsPort: DEFAULT_AGFS_PORT,
+ vlmModel: DEFAULT_VLM_MODEL,
+ embeddingModel: DEFAULT_EMBEDDING_MODEL,
+ };
+
+ if (pluginMode === "local") {
// ════════════════════════════════════════════
// Phase 3: Check & install openviking module
// ════════════════════════════════════════════
@@ -742,13 +850,6 @@ Env vars:
const ovConf = await checkOvvConf();
const ovConfPath = ovConf.path;
- let ovOpts = {
- apiKey: process.env.OPENVIKING_ARK_API_KEY || "",
- serverPort: DEFAULT_SERVER_PORT,
- agfsPort: DEFAULT_AGFS_PORT,
- vlmModel: DEFAULT_VLM_MODEL,
- embeddingModel: DEFAULT_EMBEDDING_MODEL,
- };
if (!ovConf.ok) {
log(`ov.conf not found: ${ovConfPath}`, "info");
@@ -790,6 +891,7 @@ Env vars:
ovOpts = { ...existingPorts, apiKey: existingKey };
}
}
+ } // end if pluginMode === "local" (Phase 3 & 4)
// ════════════════════════════════════════════
// Phase 5: Deploy plugin & finalize
@@ -811,18 +913,28 @@ Env vars:
pluginPath = PLUGIN_DEST;
}
- await configureOpenclaw(pluginPath, ovOpts?.serverPort);
- await writeOpenvikingEnv();
+ const installMode = (repoRoot && existsSync(join(repoRoot, "examples", "openclaw-memory-plugin", "index.ts"))) ? "link" : "download";
+ await configureOpenclaw(pluginPath, ovOpts?.serverPort, installMode, pluginMode, remoteOpts);
+
+ if (pluginMode === "local") {
+ await writeOpenvikingEnv();
+ }
// Done
console.log("\n╔══════════════════════════════════════════════════════════╗");
console.log("║ \u2705 Setup complete! ║");
console.log("╚══════════════════════════════════════════════════════════╝");
- console.log("\nTo start OpenClaw with memory:");
- if (IS_WIN) {
- console.log(' call "%USERPROFILE%\\.openclaw\\openviking.env.bat" && openclaw gateway');
+ if (pluginMode === "local") {
+ console.log("\nTo start OpenClaw with memory:");
+ if (IS_WIN) {
+ console.log(' call "%USERPROFILE%\\.openclaw\\openviking.env.bat" && openclaw gateway');
+ } else {
+ console.log(` source ${OPENCLAW_DIR}/openviking.env && openclaw gateway`);
+ }
} else {
- console.log(" source ~/.openclaw/openviking.env && openclaw gateway");
+ console.log("\nTo start OpenClaw with memory (remote mode):");
+ console.log(" openclaw gateway");
+ console.log(`\nRemote server: ${remoteOpts.baseUrl}`);
}
console.log("\nTo verify:");
console.log(" openclaw status");
diff --git a/examples/openclaw-memory-plugin/skills/install-openviking-memory/SKILL.md b/examples/openclaw-memory-plugin/skills/install-openviking-memory/SKILL.md
index 4a70a7442..e5789b052 100644
--- a/examples/openclaw-memory-plugin/skills/install-openviking-memory/SKILL.md
+++ b/examples/openclaw-memory-plugin/skills/install-openviking-memory/SKILL.md
@@ -1,282 +1,118 @@
---
-name: install-openviking-memory
-description: Install and configure OpenViking as the long-term memory backend for OpenClaw. Run this skill once to set up persistent memory that automatically remembers and recalls context across conversations. Trigger when the user asks to "install openviking", "set up memory", or "enable long-term memory".
-compatibility: OpenClaw installed (npm install -g openclaw), Python >= 3.10, Node.js >= 22
+name: openviking-memory
+description: OpenViking long-term memory plugin guide. Once installed, the plugin automatically remembers important facts from conversations and recalls relevant context before responding.
---
-# Install OpenViking Memory for OpenClaw
+# OpenViking Memory Guide
-This skill installs [OpenViking](https://github.com/volcengine/OpenViking) as the memory backend for OpenClaw. After installation, OpenClaw will automatically **remember** facts from conversations and **recall** relevant context.
+## How It Works
-> **For AI Agents:** Follow the steps below **in order**. Run each command, check the output, and only proceed when the step passes. Ask the user for input only where indicated with **[ASK USER]**.
+- **Auto-Capture**: At the end of a conversation, automatically extracts memories from user messages
+ - `semantic` mode: captures all qualifying user text, relying on OpenViking's extraction pipeline to filter
+ - `keyword` mode: only captures text matching trigger words (e.g. "remember", "preference", etc.)
+- **Auto-Recall**: Before a conversation starts, automatically searches for relevant memories and injects them into context
----
-
-## Step 1: Check Prerequisites
+## Available Tools
-Run **all** checks below. Every check must pass before continuing.
+### memory_recall — Search Memories
-### 1.1 Check Node.js (>= 22)
-
-```bash
-node -v
-```
+Searches long-term memories in OpenViking, returns relevant results.
-- **Pass:** Output shows `v22.x.x` or higher.
-- **Fail:** Tell the user: "Node.js >= 22 is required. Install it from https://nodejs.org/ or use nvm: `nvm install 22`"
+| Parameter | Required | Description |
+|-----------|----------|-------------|
+| `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) |
-### 1.2 Check Python (>= 3.10)
+Example: User asks "What programming language did I say I like?"
-**Linux / macOS:**
+### memory_store — Manual Store
-```bash
-python3 --version
-```
+Writes text to an OpenViking session and runs memory extraction.
-**Windows:**
+| Parameter | Required | Description |
+|-----------|----------|-------------|
+| `text` | Yes | Information text to store |
+| `role` | No | Session role (default `user`) |
+| `sessionId` | No | Existing OpenViking session ID |
-```powershell
-python --version
-```
+Example: User says "Remember my email is [email protected]"
-- **Pass:** Output shows `Python 3.10.x` or higher.
-- **Fail:** Tell the user: "Python >= 3.10 is required. See INSTALL.md for installation instructions, or build from source: https://www.python.org/downloads/"
+### memory_forget — Delete Memories
-### 1.3 Check Build Tools (cmake, g++)
+Delete by exact URI, or search and delete.
-```bash
-cmake --version
-g++ --version
-```
-
-- **Pass:** Both commands return version info.
-- **Fail:** Tell the user which tool is missing and how to install:
- - RHEL/CentOS/openEuler: `sudo dnf install -y gcc gcc-c++ cmake make`
- - Ubuntu/Debian: `sudo apt install -y build-essential cmake`
- - **These tools are required** — OpenClaw's `node-llama-cpp` dependency compiles C++ during installation, and OpenViking also has C++ extensions.
-
-### 1.4 Check OpenClaw
-
-```bash
-openclaw --version
-```
+| Parameter | Required | Description |
+|-----------|----------|-------------|
+| `uri` | No | Exact memory URI (direct delete) |
+| `query` | No | Search query (find then delete) |
+| `targetUri` | No | Search scope URI |
+| `limit` | No | Search limit (default 5) |
+| `scoreThreshold` | No | Minimum relevance score |
-- **Pass:** Shows version output.
-- **Fail:** Tell the user: "OpenClaw is required. Install with: `npm install -g openclaw` (if downloads are slow: `npm install -g openclaw --registry=https://registry.npmmirror.com`). After installing, run `openclaw onboard` to configure your LLM."
-
-### 1.5 Check Go (>= 1.19) — only for source install on Linux
-
-> Skip this check if the user will install via `pip install openviking --upgrade --force-reinstall` (PyPI pre-built package).
-
-```bash
-go version
-```
-
-- **Pass:** Output shows `go1.19.x` or higher.
-- **Fail:** Tell the user: "Go >= 1.19 is required for source installation on Linux (to compile AGFS). Download from https://go.dev/dl/ — see INSTALL.md for detailed steps."
-
----
-
-## Step 2: Clone and Install OpenViking
-
-### 2.1 Clone Repository
-
-If the OpenViking repo is not already present:
-
-```bash
-git clone https://github.com/volcengine/OpenViking.git
-cd OpenViking
-```
+Example: User says "Forget my phone number"
-### 2.2 Install Python Package
+## Configuration
-Two options — choose based on the user's needs:
+| Field | Default | Description |
+|-------|---------|-------------|
+| `mode` | `remote` | `local` (start local server) or `remote` (connect to remote) |
+| `baseUrl` | `http://127.0.0.1:1933` | OpenViking server URL (remote mode) |
+| `apiKey` | — | OpenViking API Key (optional) |
+| `agentId` | `openclaw-<hostname>` | Identifies this agent (auto-generated, persisted to `~/.openviking/.agent-id`) |
+| `configPath` | `~/.openviking/ov.conf` | Config file path (local mode) |
+| `port` | `1933` | Local server port (local mode) |
+| `targetUri` | `viking://user/memories` | Default search scope |
+| `autoCapture` | `true` | Automatically capture memories |
+| `captureMode` | `semantic` | Capture mode: `semantic` / `keyword` |
+| `captureMaxLength` | `24000` | Maximum text length per capture |
+| `autoRecall` | `true` | Automatically recall and inject context |
+| `recallLimit` | `6` | Maximum memories injected during auto-recall |
+| `recallScoreThreshold` | `0.01` | Minimum relevance score for recall |
+| `ingestReplyAssist` | `true` | Add reply guidance when detecting multi-party conversation text |
-#### Option A: Install from PyPI (recommended, no Go needed)
-
-```bash
-python3 -m pip install openviking --upgrade --force-reinstall
-```
-
-#### Option B: Install from Source (developer mode)
-
-Requires Go >= 1.19 on Linux (check passed in Step 1.5).
-
-**Linux / macOS:**
-
-```bash
-python3 -m pip install -e . --force-reinstall
-```
-
-**Windows:**
-
-```powershell
-python -m pip install -e . --force-reinstall
-```
-
-> If pip downloads are slow, suggest using a mirror:
-> `python3 -m pip install openviking --upgrade --force-reinstall -i https://pypi.tuna.tsinghua.edu.cn/simple`
-
-### 2.3 Verify Installation
-
-**Linux / macOS:**
-
-```bash
-python3 -c "import openviking; print('openviking module: ok')"
-```
-
-**Windows:**
-
-```powershell
-python -c "import openviking; print('openviking module: ok')"
-```
-
-- **Pass:** Prints `openviking module: ok`.
-- **Fail — multiple Python versions:** Ask the user which Python to use, then install with that path: `/path/to/python3.11 -m pip install openviking --upgrade --force-reinstall`
-- **Fail — `TypeError: unsupported operand type(s) for |`:** Python version is below 3.10. The user needs to upgrade.
-- **Fail — `Go compiler not found`:** Go is not installed (source install only). See Step 1.5.
-
----
-
-## Step 3: Run the Setup Helper
-
-From the OpenViking repo root:
-
-```bash
-npx ./examples/openclaw-memory-plugin/setup-helper
-```
-
-The helper will interactively prompt for:
-
-1. **Workspace path** — data storage location (default: absolute path of `~/.openviking/data`, auto-detected)
-2. **Volcengine Ark API Key** — **[ASK USER]** Direct them to https://console.volcengine.com/ark if they don't have one
-3. **VLM model** — default `doubao-seed-2-0-pro-260215`, press Enter to accept
-4. **Embedding model** — default `doubao-embedding-vision-250615`, press Enter to accept
-5. **Server ports** — default 1933 (HTTP) and 1833 (AGFS), press Enter to accept
-
-The helper will automatically:
-- Create `~/.openviking/ov.conf`
-- Deploy the `memory-openviking` plugin into OpenClaw
-- Configure OpenClaw to use local mode
-- Write `~/.openclaw/openviking.env` (Linux/macOS) or `openviking.env.bat` (Windows)
-
-Wait for `Setup complete!` before proceeding.
-
----
-
-## Step 4: Start OpenClaw with Memory
-
-**Always load the env file first**, then start the gateway:
-
-**Linux / macOS:**
+## Daily Operations
```bash
+# Start (local mode: source env first)
source ~/.openclaw/openviking.env && openclaw gateway
-```
-
-**Windows (cmd):**
-
-```cmd
-call "%USERPROFILE%\.openclaw\openviking.env.bat" && openclaw gateway
-```
-Wait a few seconds. Verify this line appears in the output:
+# Start (remote mode: no env needed)
+openclaw gateway
-```
-[gateway] memory-openviking: local server started (http://127.0.0.1:1933, ...)
-```
-
-- **Pass:** Tell the user: "OpenViking memory is now active. I will automatically remember important facts from our conversations and recall them when relevant."
-- **Fail — `health check timeout`:** A stale process is blocking the port. Fix with:
- ```bash
- lsof -ti tcp:1933 tcp:1833 | xargs kill -9
- source ~/.openclaw/openviking.env && openclaw gateway
- ```
-
----
-
-## Step 5: Verify (Optional)
-
-```bash
+# Check status
openclaw status
-```
-
-The **Memory** line should show: `enabled (plugin memory-openviking)`
-
----
-
-## Troubleshooting Quick Reference
-
-| Symptom | Cause | Fix |
-|---------|-------|-----|
-| `cmake not found` during npm install | Missing build tools | `sudo dnf install -y gcc gcc-c++ cmake make` |
-| `Python.h: No such file or directory` | Missing Python dev headers | `sudo dnf install -y python3-devel` (or `python3.11-devel`) |
-| `Go compiler not found` | Go not installed | Install Go >= 1.19 from https://go.dev/dl/ |
-| `dial tcp: i/o timeout` (Go modules) | Network issue | `go env -w GOPROXY=https://goproxy.cn,direct` |
-| `ERR_INVALID_URL` (npm) | Proxy missing `http://` prefix | `export https_proxy=http://host:port` |
-| `extracted 0 memories` | Wrong API key or model name | Check `api_key` and `model` in `~/.openviking/ov.conf` |
-| `health check timeout` | Stale process on port | Kill with `lsof -ti tcp:1933 tcp:1833 \| xargs kill -9` |
-| Plugin not loaded | Env file not sourced | Run `source ~/.openclaw/openviking.env` before gateway |
-
----
-
-## Daily Usage
-
-Each time the user wants to start OpenClaw with memory:
-
-**Linux / macOS:**
-
-```bash
-source ~/.openclaw/openviking.env && openclaw gateway
-```
-
-**Windows (cmd):**
-
-```cmd
-call "%USERPROFILE%\.openclaw\openviking.env.bat" && openclaw gateway
-```
-> Suggest adding an alias for convenience:
-> ```bash
-> echo 'alias openclaw-start="source ~/.openclaw/openviking.env && openclaw gateway"' >> ~/.bashrc
-> ```
-
-### Enable/Disable the Memory Plugin Slot
-
-Disable the memory plugin:
-
-```bash
+# Disable memory
openclaw config set plugins.slots.memory none
-```
-
-Enable the OpenViking memory plugin:
-```bash
+# Enable memory
openclaw config set plugins.slots.memory memory-openviking
```
-If the gateway is already running, restart it after changing the slot.
+Restart the gateway after changing the slot.
----
-
-## Uninstall
+## Multi-Instance Support
-**Linux / macOS:**
+If you have multiple OpenClaw instances, use `--workdir` to target a specific one:
```bash
-lsof -ti tcp:1933 tcp:1833 tcp:18789 | xargs kill -9
-npm uninstall -g openclaw
-rm -rf ~/.openclaw
-python3 -m pip uninstall openviking -y
-rm -rf ~/.openviking
-```
+# Install script
+curl -fsSL ... | bash -s -- --workdir ~/.openclaw-openclaw-second
-**Windows (cmd):**
+# Setup helper
+npx ./examples/openclaw-memory-plugin/setup-helper --workdir ~/.openclaw-openclaw-second
-```cmd
-for /f "tokens=5" %a in ('netstat -ano ^| findstr "LISTENING" ^| findstr ":1933 :1833 :18789"') do taskkill /PID %a /F
-npm uninstall -g openclaw
-rmdir /s /q "%USERPROFILE%\.openclaw"
-python -m pip uninstall openviking -y
-rmdir /s /q "%USERPROFILE%\.openviking"
+# Manual config (prefix openclaw commands)
+OPENCLAW_STATE_DIR=~/.openclaw-openclaw-second openclaw config set ...
```
+
+## Troubleshooting
+
+| Symptom | Cause | Fix |
+|---------|-------|-----|
+| `extracted 0 memories` | Wrong API Key or model name | Check `api_key` and `model` in `ov.conf` |
+| `port occupied` | Port used by another process | Change port: `openclaw config set plugins.entries.memory-openviking.config.port 1934` |
+| Plugin not loaded | Env file not sourced or slot not configured | Check `openclaw status` output |
+| Inaccurate recall | recallScoreThreshold too low | Increase threshold or adjust recallLimit |
diff --git a/examples/openclaw-memory-plugin/text-utils.ts b/examples/openclaw-memory-plugin/text-utils.ts
new file mode 100644
index 000000000..40f224a45
--- /dev/null
+++ b/examples/openclaw-memory-plugin/text-utils.ts
@@ -0,0 +1,363 @@
+import type { CaptureMode } from "./client.js";
+
+export const MEMORY_TRIGGERS = [
+ /remember|preference|prefer|important|decision|decided|always|never/i,
+ /记住|偏好|喜欢|喜爱|崇拜|讨厌|害怕|重要|决定|总是|永远|优先|习惯|爱好|擅长|最爱|不喜欢/i,
+ /[\w.-]+@[\w.-]+\.\w+/,
+ /\+\d{10,}/,
+ /(?:我|my)\s*(?:是|叫|名字|name|住在|live|来自|from|生日|birthday|电话|phone|邮箱|email)/i,
+ /(?:我|i)\s*(?:喜欢|崇拜|讨厌|害怕|擅长|不会|爱|恨|想要|需要|希望|觉得|认为|相信)/i,
+ /(?:favorite|favourite|love|hate|enjoy|dislike|admire|idol|fan of)/i,
+];
+
+const CJK_CHAR_REGEX = /[\u3040-\u30ff\u3400-\u9fff\uf900-\ufaff\uac00-\ud7af]/;
+const RELEVANT_MEMORIES_BLOCK_RE = /<relevant-memories>[\s\S]*?<\/relevant-memories>/gi;
+const CONVERSATION_METADATA_BLOCK_RE =
+ /(?:^|\n)\s*(?:Conversation info|Conversation metadata|会话信息|对话信息)\s*(?:\([^)]+\))?\s*:\s*```[\s\S]*?```/gi;
+/** Strips "Sender (untrusted metadata): ```json ... ```" so capture sends clean text to OpenViking extract. */
+const SENDER_METADATA_BLOCK_RE = /Sender\s*\([^)]*\)\s*:\s*```[\s\S]*?```/gi;
+const FENCED_JSON_BLOCK_RE = /```json\s*([\s\S]*?)```/gi;
+const METADATA_JSON_KEY_RE =
+ /"(session|sessionid|sessionkey|conversationid|channel|sender|userid|agentid|timestamp|timezone)"\s*:/gi;
+const LEADING_TIMESTAMP_PREFIX_RE = /^\s*\[[^\]\n]{1,120}\]\s*/;
+const COMMAND_TEXT_RE = /^\/[a-z0-9_-]{1,64}\b/i;
+const NON_CONTENT_TEXT_RE = /^[\p{P}\p{S}\s]+$/u;
+const SUBAGENT_CONTEXT_RE = /^\s*\[Subagent Context\]/i;
+const MEMORY_INTENT_RE = /记住|记下|remember|save|store|偏好|preference|规则|rule|事实|fact/i;
+const QUESTION_CUE_RE =
+ /[??]|\b(?:what|when|where|who|why|how|which|can|could|would|did|does|is|are)\b|^(?:请问|能否|可否|怎么|如何|什么时候|谁|什么|哪|是否)/i;
+const SPEAKER_TAG_RE = /(?:^|\s)([A-Za-z\u4e00-\u9fa5][A-Za-z0-9_\u4e00-\u9fa5-]{1,30}):\s/g;
+
+export const CAPTURE_LIMIT = 3;
+
+function resolveCaptureMinLength(text: string): number {
+ return CJK_CHAR_REGEX.test(text) ? 4 : 10;
+}
+
+function looksLikeMetadataJsonBlock(content: string): boolean {
+ const matchedKeys = new Set<string>();
+ const matches = content.matchAll(METADATA_JSON_KEY_RE);
+ for (const match of matches) {
+ const key = (match[1] ?? "").toLowerCase();
+ if (key) {
+ matchedKeys.add(key);
+ }
+ }
+ return matchedKeys.size >= 3;
+}
+
+export function sanitizeUserTextForCapture(text: string): string {
+ return text
+ .replace(RELEVANT_MEMORIES_BLOCK_RE, " ")
+ .replace(CONVERSATION_METADATA_BLOCK_RE, " ")
+ .replace(SENDER_METADATA_BLOCK_RE, " ")
+ .replace(FENCED_JSON_BLOCK_RE, (full, inner) =>
+ looksLikeMetadataJsonBlock(String(inner ?? "")) ? " " : full,
+ )
+ .replace(LEADING_TIMESTAMP_PREFIX_RE, "")
+ .replace(/\u0000/g, "")
+ .replace(/\s+/g, " ")
+ .trim();
+}
+
+export function looksLikeQuestionOnlyText(text: string): boolean {
+ if (!QUESTION_CUE_RE.test(text) || MEMORY_INTENT_RE.test(text)) {
+ return false;
+ }
+ // Multi-speaker transcripts often contain many "?" but should still be captured.
+ const speakerTags = text.match(/[A-Za-z\u4e00-\u9fa5]{2,20}:\s/g) ?? [];
+ if (speakerTags.length >= 2 || text.length > 280) {
+ return false;
+ }
+ return true;
+}
+
+export type TranscriptLikeIngestDecision = {
+ shouldAssist: boolean;
+ reason: string;
+ normalizedText: string;
+ speakerTurns: number;
+ chars: number;
+};
+
+function countSpeakerTurns(text: string): number {
+ let count = 0;
+ for (const _match of text.matchAll(SPEAKER_TAG_RE)) {
+ count += 1;
+ }
+ return count;
+}
+
+export function isTranscriptLikeIngest(
+ text: string,
+ options: {
+ minSpeakerTurns: number;
+ minChars: number;
+ },
+): TranscriptLikeIngestDecision {
+ const normalizedText = sanitizeUserTextForCapture(text.trim());
+ if (!normalizedText) {
+ return {
+ shouldAssist: false,
+ reason: "empty_text",
+ normalizedText,
+ speakerTurns: 0,
+ chars: 0,
+ };
+ }
+
+ if (COMMAND_TEXT_RE.test(normalizedText)) {
+ return {
+ shouldAssist: false,
+ reason: "command_text",
+ normalizedText,
+ speakerTurns: 0,
+ chars: normalizedText.length,
+ };
+ }
+
+ if (SUBAGENT_CONTEXT_RE.test(normalizedText)) {
+ return {
+ shouldAssist: false,
+ reason: "subagent_context",
+ normalizedText,
+ speakerTurns: 0,
+ chars: normalizedText.length,
+ };
+ }
+
+ if (NON_CONTENT_TEXT_RE.test(normalizedText)) {
+ return {
+ shouldAssist: false,
+ reason: "non_content_text",
+ normalizedText,
+ speakerTurns: 0,
+ chars: normalizedText.length,
+ };
+ }
+
+ if (looksLikeQuestionOnlyText(normalizedText)) {
+ return {
+ shouldAssist: false,
+ reason: "question_text",
+ normalizedText,
+ speakerTurns: 0,
+ chars: normalizedText.length,
+ };
+ }
+
+ const chars = normalizedText.length;
+ if (chars < options.minChars) {
+ return {
+ shouldAssist: false,
+ reason: "chars_below_threshold",
+ normalizedText,
+ speakerTurns: 0,
+ chars,
+ };
+ }
+
+ const speakerTurns = countSpeakerTurns(normalizedText);
+ if (speakerTurns < options.minSpeakerTurns) {
+ return {
+ shouldAssist: false,
+ reason: "speaker_turns_below_threshold",
+ normalizedText,
+ speakerTurns,
+ chars,
+ };
+ }
+
+ return {
+ shouldAssist: true,
+ reason: "transcript_like_ingest",
+ normalizedText,
+ speakerTurns,
+ chars,
+ };
+}
+
+function normalizeDedupeText(text: string): string {
+ return text.toLowerCase().replace(/\s+/g, " ").trim();
+}
+
+function normalizeCaptureDedupeText(text: string): string {
+ return normalizeDedupeText(text).replace(/[\p{P}\p{S}]+/gu, " ").replace(/\s+/g, " ").trim();
+}
+
+export function pickRecentUniqueTexts(texts: string[], limit: number): string[] {
+ if (limit <= 0 || texts.length === 0) {
+ return [];
+ }
+ const seen = new Set<string>();
+ const picked: string[] = [];
+ for (let i = texts.length - 1; i >= 0; i -= 1) {
+ const text = texts[i];
+ const key = normalizeCaptureDedupeText(text);
+ if (!key || seen.has(key)) {
+ continue;
+ }
+ seen.add(key);
+ picked.push(text);
+ if (picked.length >= limit) {
+ break;
+ }
+ }
+ return picked.reverse();
+}
+
+export function getCaptureDecision(text: string, mode: CaptureMode, captureMaxLength: number): {
+ shouldCapture: boolean;
+ reason: string;
+ normalizedText: string;
+} {
+ const trimmed = text.trim();
+ const normalizedText = sanitizeUserTextForCapture(trimmed);
+ const hadSanitization = normalizedText !== trimmed;
+ if (!normalizedText) {
+ return {
+ shouldCapture: false,
+ reason: /<relevant-memories>/i.test(trimmed) ? "injected_memory_context_only" : "empty_text",
+ normalizedText: "",
+ };
+ }
+
+ const compactText = normalizedText.replace(/\s+/g, "");
+ const minLength = resolveCaptureMinLength(compactText);
+ if (compactText.length < minLength || normalizedText.length > captureMaxLength) {
+ return {
+ shouldCapture: false,
+ reason: "length_out_of_range",
+ normalizedText,
+ };
+ }
+
+ if (COMMAND_TEXT_RE.test(normalizedText)) {
+ return {
+ shouldCapture: false,
+ reason: "command_text",
+ normalizedText,
+ };
+ }
+
+ if (NON_CONTENT_TEXT_RE.test(normalizedText)) {
+ return {
+ shouldCapture: false,
+ reason: "non_content_text",
+ normalizedText,
+ };
+ }
+ if (SUBAGENT_CONTEXT_RE.test(normalizedText)) {
+ return {
+ shouldCapture: false,
+ reason: "subagent_context",
+ normalizedText,
+ };
+ }
+ if (looksLikeQuestionOnlyText(normalizedText)) {
+ return {
+ shouldCapture: false,
+ reason: "question_text",
+ normalizedText,
+ };
+ }
+
+ if (mode === "keyword") {
+ for (const trigger of MEMORY_TRIGGERS) {
+ if (trigger.test(normalizedText)) {
+ return {
+ shouldCapture: true,
+ reason: hadSanitization
+ ? `matched_trigger_after_sanitize:${trigger.toString()}`
+ : `matched_trigger:${trigger.toString()}`,
+ normalizedText,
+ };
+ }
+ }
+ return {
+ shouldCapture: false,
+ reason: hadSanitization ? "no_trigger_matched_after_sanitize" : "no_trigger_matched",
+ normalizedText,
+ };
+ }
+
+ return {
+ shouldCapture: true,
+ reason: hadSanitization ? "semantic_candidate_after_sanitize" : "semantic_candidate",
+ normalizedText,
+ };
+}
+
+export function extractTextsFromUserMessages(messages: unknown[]): string[] {
+ const texts: string[] = [];
+ for (const msg of messages) {
+ if (!msg || typeof msg !== "object") {
+ continue;
+ }
+ const msgObj = msg as Record<string, unknown>;
+ if (msgObj.role !== "user") {
+ continue;
+ }
+ const content = msgObj.content;
+ if (typeof content === "string") {
+ texts.push(content);
+ continue;
+ }
+ if (Array.isArray(content)) {
+ for (const block of content) {
+ if (!block || typeof block !== "object") {
+ continue;
+ }
+ const blockObj = block as Record<string, unknown>;
+ if (blockObj.type === "text" && typeof blockObj.text === "string") {
+ texts.push(blockObj.text);
+ }
+ }
+ }
+ }
+ return texts;
+}
+
+/**
+ * 提取从 startIndex 开始的新消息(user + assistant),返回格式化的文本。
+ */
+export function extractNewTurnTexts(
+ messages: unknown[],
+ startIndex: number,
+): { texts: string[]; newCount: number } {
+ const texts: string[] = [];
+ let count = 0;
+ for (let i = startIndex; i < messages.length; i++) {
+ const msg = messages[i] as Record<string, unknown>;
+ if (!msg || typeof msg !== "object") continue;
+ const role = msg.role as string;
+ if (role !== "user" && role !== "assistant") continue;
+ count++;
+ const content = msg.content;
+ if (typeof content === "string" && content.trim()) {
+ texts.push(`[${role}]: ${content.trim()}`);
+ } else if (Array.isArray(content)) {
+ for (const block of content) {
+ const b = block as Record<string, unknown>;
+ if (b?.type === "text" && typeof b.text === "string") {
+ texts.push(`[${role}]: ${(b.text as string).trim()}`);
+ }
+ }
+ }
+ }
+ return { texts, newCount: count };
+}
+
+export function extractLatestUserText(messages: unknown[] | undefined): string {
+ if (!messages || messages.length === 0) {
+ return "";
+ }
+ const texts = extractTextsFromUserMessages(messages);
+ for (let i = texts.length - 1; i >= 0; i -= 1) {
+ const normalized = sanitizeUserTextForCapture(texts[i] ?? "");
+ if (normalized) {
+ return normalized;
+ }
+ }
+ return "";
+}
diff --git a/examples/openclaw-memory-plugin/tsconfig.json b/examples/openclaw-memory-plugin/tsconfig.json
new file mode 100644
index 000000000..158c20095
--- /dev/null
+++ b/examples/openclaw-memory-plugin/tsconfig.json
@@ -0,0 +1,12 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "Node16",
+ "moduleResolution": "Node16",
+ "strict": true,
+ "noEmit": true,
+ "skipLibCheck": true,
+ "types": ["node"]
+ },
+ "include": ["*.ts"]
+}
diff --git a/openviking/prompts/templates/compression/memory_extraction.yaml b/openviking/prompts/templates/compression/memory_extraction.yaml
index e143e78a2..da1ff2754 100644
--- a/openviking/prompts/templates/compression/memory_extraction.yaml
+++ b/openviking/prompts/templates/compression/memory_extraction.yaml
@@ -54,6 +54,19 @@ template: |
- Instruction-like user requests about assistant behavior (language/style/format/tooling) are extraction targets.
- If such a request implies ongoing behavior, extract it as `preferences`; do not drop it as a mere command.
- **Tool/Skill Call Records**: The conversation may contain `[ToolCall]` entries with tool/skill usage details. When present, extract relevant tool/skill memories.
+ - **Exhaustive extraction**: A single message may contain multiple independent facts.
+ Extract EACH as a separate memory item. Do not merge unrelated facts into one summary.
+ Count the distinct factual claims in each message and ensure each one is captured.
+ - **Detail preservation**: Always preserve specific proper nouns, parameter names, numeric
+ values, version numbers, and technical terms verbatim. The value of a memory lies in its
+ specificity. A memory that says "solved problem X using method Y" is useful; a memory
+ that says "handled problem X" is nearly useless because it loses the solution.
+ - **High recall**: When uncertain whether something is worth extracting, extract it.
+ The downstream deduplication system handles redundancy. Missing a valuable memory is
+ worse than creating a slightly redundant one.
+ - **Temporal precision**: Never use relative time expressions ("today", "recently",
+ "last week") in memory content. Convert to absolute references or omit the time
+ if unknown. Memories persist indefinitely; relative time becomes meaningless.
{% if feedback %}
## User Feedback
@@ -68,9 +81,13 @@ template: |
- ✅ **Specific and clear**: Has concrete details, not vague generalizations
## What is NOT worth remembering?
- - ❌ **General knowledge**: "Personalized service is core to romantic vacations" (domain knowledge, not personalized memory)
- - ❌ **Temporary information**: One-time questions or conversations
- - ❌ **Vague information**: "User has questions about a feature" (no specific details)
+ - ❌ **General domain knowledge**: Information true for everyone, not specific to this user.
+ Example: "Redis is an in-memory database" is general knowledge.
+ But "User's team uses Redis with 10-minute TTL for product cache" IS personalized.
+ - ❌ **Content-free utterances**: Pure greetings, acknowledgments, or filler with zero
+ informational content ("Hello", "Thanks", "OK").
+ - ❌ **Completely vague statements**: No concrete details at all.
+ "User has some concerns" (what concerns? about what?)
# Memory Classification
@@ -115,20 +132,36 @@ template: |
- This granularity is required so future updates/conflicts can affect only the
relevant memory without damaging unrelated preferences.
- **entities** - Entities (continuously existing nouns)
- - Core: Describes "current state of something"
- - Characteristics: Entities with lifecycle (person/project/organization)
- - Test: Can it be described as "XXX's state is..."
-
- **events** - Events (things that happened)
- - Core: Describes "what happened"
- - Characteristics: Has time point, is action completion
- - Test: Can it be described as "XXX did/completed/happened..."
-
- **cases** - Cases (problem + solution)
- - Core: Describes "how a specific problem was solved"
- - Characteristics: One-time scenario, specific solution
- - Test: Does it contain "problem → solution" structure
+ **entities** - Entities (named things with attributes)
+ - Core: Describes "what is this named thing and what are its attributes"
+ - Characteristics: Named entities that exist independently of the user's preferences
+ (people, projects, organizations, systems, teams, technologies-as-systems)
+ - Test: Does it describe a THING (not a preference, not an event, not a problem)?
+ - Includes: project descriptions, system architectures, team compositions,
+ organization structures, named tools/platforms with their configurations
+ - Note: "Our system uses tech stack X" describes the SYSTEM → entities.
+ "I prefer using tool X" describes USER preference → preferences.
+
+ **events** - Events (time-bound activities: past, present, or future)
+ - Core: Describes "what happened", "what is happening", or "what is planned"
+ - Characteristics: Has a time dimension (creation time, occurrence time, or deadline);
+ covers completed, ongoing, and planned activities
+ - Test: Can it be described as "XXX did/is doing/plans to do..."
+ - Includes: past decisions, completed activities, ongoing activities
+ (e.g., currently reading a book), planned future activities, deadlines,
+ goals with timeframes
+ - Note: An ongoing activity like "currently reading book X" is an event
+ (time-bound), not a preference. A plan like "tonight will optimize X"
+ is also an event (has creation time and intended execution time).
+
+ **cases** - Cases (problem → cause/solution/outcome)
+ - Core: Describes a specific problem and how it was diagnosed, caused, or resolved
+ - Characteristics: Contains a concrete problem description AND at least one of:
+ root cause, solution method, workaround, or outcome/impact
+ - Test: Does it follow a "problem → cause/solution/outcome" structure?
+ - Note: Even if the problem seems minor or one-time, extract it if both the
+ problem and its resolution/cause are stated. The specific details
+ (error messages, parameter values, method names) are the most valuable part.
**patterns** - Patterns (reusable processes)
- Core: Describes "what process to follow in what situation"
@@ -162,6 +195,12 @@ template: |
- "User prefers X" → preferences (not profile)
- "Encountered problem A, used solution B" → cases (not events)
- "General process for handling certain problems" → patterns (not cases)
+ - "We use tool/platform/framework X for purpose Y" → entities (describes a system/setup)
+ - "I prefer/like using tool X" → preferences (personal choice)
+ - "Currently reading/learning/studying X" → events (ongoing time-bound activity)
+ - "Bug: misconfigured parameter X caused issue Y" → cases (problem + cause)
+ - "User's daily routine: do X in morning, Y in afternoon" → preferences (habitual pattern)
+ - "Colleague/teammate X is responsible for Y" → entities (describes a person)
# Three-Level Structure
diff --git a/third_party/agfs/agfs-sdk/python/pyagfs/binding_client.py b/third_party/agfs/agfs-sdk/python/pyagfs/binding_client.py
index 0078c7ec5..1287b9e91 100644
--- a/third_party/agfs/agfs-sdk/python/pyagfs/binding_client.py
+++ b/third_party/agfs/agfs-sdk/python/pyagfs/binding_client.py
@@ -387,6 +387,7 @@ class AGFSBindingClient:
recursive: bool = False,
case_insensitive: bool = False,
stream: bool = False,
+ node_limit: Optional[int] = None,
):
"""Search for a pattern in files."""
raise AGFSNotSupportedError("Grep not supported in binding mode")