human-like-mem-openclaw-plugin 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +190 -0
- package/README.md +207 -0
- package/README_ZH.md +152 -0
- package/index.js +435 -0
- package/openclaw.plugin.json +135 -0
- package/package.json +50 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to the Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
Copyright 2025 Personal Flow Team
|
|
179
|
+
|
|
180
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
181
|
+
you may not use this file except in compliance with the License.
|
|
182
|
+
You may obtain a copy of the License at
|
|
183
|
+
|
|
184
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
185
|
+
|
|
186
|
+
Unless required by applicable law or agreed to in writing, software
|
|
187
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
188
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
189
|
+
See the License for the specific language governing permissions and
|
|
190
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
# Human-Like Memory Plugin for OpenClaw
|
|
2
|
+
|
|
3
|
+
一个用于 OpenClaw 的长期记忆插件,自动在对话前召回相关记忆,并在对话后持久化新记忆。
|
|
4
|
+
|
|
5
|
+
## 功能特性
|
|
6
|
+
|
|
7
|
+
- **自动记忆召回**: 在 Agent 开始前自动检索与当前对话相关的历史记忆
|
|
8
|
+
- **自动记忆存储**: 在对话结束后自动将对话保存为新的记忆
|
|
9
|
+
- **全局/会话记忆**: 支持跨会话的全局记忆检索或仅当前会话的记忆
|
|
10
|
+
- **灵活配置**: 支持通过环境变量或配置文件自定义所有参数
|
|
11
|
+
- **异步模式**: 支持异步模式,不阻塞对话流程
|
|
12
|
+
|
|
13
|
+
## 安装
|
|
14
|
+
|
|
15
|
+
### 方式 A: 本地路径安装 (推荐,适合离线环境)
|
|
16
|
+
|
|
17
|
+
1. 将插件文件夹复制到 OpenClaw 扩展目录:
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
# 复制到默认扩展目录
|
|
21
|
+
cp -r human-like-mem-openclaw-plugin ~/.openclaw/extensions/
|
|
22
|
+
|
|
23
|
+
# 或者放到任意位置,然后配置路径
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
2. 编辑 `~/.openclaw/openclaw.json`:
|
|
27
|
+
|
|
28
|
+
```json
|
|
29
|
+
{
|
|
30
|
+
"plugins": {
|
|
31
|
+
"entries": {
|
|
32
|
+
"human-like-mem-openclaw-plugin": { "enabled": true }
|
|
33
|
+
},
|
|
34
|
+
"load": {
|
|
35
|
+
"paths": ["~/.openclaw/extensions/human-like-mem-openclaw-plugin"]
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
### 方式 B: 从 npm 安装
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
npm install human-like-mem-openclaw-plugin
|
|
45
|
+
# 或
|
|
46
|
+
yarn add human-like-mem-openclaw-plugin
|
|
47
|
+
# 或
|
|
48
|
+
pnpm add human-like-mem-openclaw-plugin
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
### 方式 C: 从 Git 仓库安装
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
npm install git+https://gitlab.ttyuyin.com/personalization_group/human-like-mem-openclaw-plugin.git
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
### 方式 D: 从 tarball 安装 (离线环境)
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
# 在有网络的机器上打包
|
|
61
|
+
npm pack
|
|
62
|
+
|
|
63
|
+
# 将 .tgz 文件拷贝到目标机器,然后安装
|
|
64
|
+
npm install ./human-like-mem-openclaw-plugin-0.1.0.tgz
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## 配置
|
|
68
|
+
|
|
69
|
+
### 1. 启用插件
|
|
70
|
+
|
|
71
|
+
编辑 `~/.openclaw/openclaw.json`:
|
|
72
|
+
|
|
73
|
+
```json
|
|
74
|
+
{
|
|
75
|
+
"plugins": {
|
|
76
|
+
"entries": {
|
|
77
|
+
"human-like-mem-openclaw-plugin": {
|
|
78
|
+
"enabled": true
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
### 2. 配置环境变量
|
|
86
|
+
|
|
87
|
+
```bash
|
|
88
|
+
# 必需配置
|
|
89
|
+
export MEMORY_SYSTEM_TOKEN="your-system-token" # 系统认证令牌
|
|
90
|
+
export MEMORY_BASE_URL="https://your-memory-api.example.com" # API 地址
|
|
91
|
+
|
|
92
|
+
# 可选配置
|
|
93
|
+
export MEMORY_USER_ID="your-user-id" # 用户标识 (默认: openclaw-user)
|
|
94
|
+
export MEMORY_AGENT_ID="your-agent-id" # Agent 标识 (默认: openclaw-agent)
|
|
95
|
+
export MEMORY_RECALL_ENABLED="true" # 启用记忆召回 (默认: true)
|
|
96
|
+
export MEMORY_ADD_ENABLED="true" # 启用记忆存储 (默认: true)
|
|
97
|
+
export MEMORY_RECALL_GLOBAL="true" # 全局记忆搜索 (默认: true)
|
|
98
|
+
export MEMORY_LIMIT_NUMBER="6" # 召回记忆数量 (默认: 6)
|
|
99
|
+
export MEMORY_MIN_SCORE="0.1" # 最低相关性分数 (默认: 0.1)
|
|
100
|
+
export MEMORY_SCENARIO="" # 记忆场景过滤
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
### 3. 完整配置参数
|
|
104
|
+
|
|
105
|
+
| 参数 | 环境变量 | 默认值 | 说明 |
|
|
106
|
+
|------|----------|--------|------|
|
|
107
|
+
| `baseUrl` | `MEMORY_BASE_URL` | - | Memory 服务 API 地址 |
|
|
108
|
+
| `systemToken` | `MEMORY_SYSTEM_TOKEN` | - | 系统认证令牌 (必需) |
|
|
109
|
+
| `userId` | `MEMORY_USER_ID` | `openclaw-user` | 用户标识 |
|
|
110
|
+
| `agentId` | `MEMORY_AGENT_ID` | `openclaw-agent` | Agent 标识 |
|
|
111
|
+
| `recallEnabled` | `MEMORY_RECALL_ENABLED` | `true` | 是否启用记忆召回 |
|
|
112
|
+
| `addEnabled` | `MEMORY_ADD_ENABLED` | `true` | 是否启用记忆存储 |
|
|
113
|
+
| `recallGlobal` | `MEMORY_RECALL_GLOBAL` | `true` | 是否全局搜索记忆 |
|
|
114
|
+
| `memoryLimitNumber` | `MEMORY_LIMIT_NUMBER` | `6` | 召回记忆的最大数量 |
|
|
115
|
+
| `minScore` | `MEMORY_MIN_SCORE` | `0.1` | 最低相关性分数阈值 |
|
|
116
|
+
| `scenario` | `MEMORY_SCENARIO` | `""` | 记忆场景过滤 |
|
|
117
|
+
| `captureStrategy` | `MEMORY_CAPTURE_STRATEGY` | `last_turn` | 消息捕获策略 |
|
|
118
|
+
| `maxMessageChars` | `MEMORY_MAX_MESSAGE_CHARS` | `20000` | 单条消息最大字符数 |
|
|
119
|
+
| `asyncMode` | `MEMORY_ASYNC_MODE` | `true` | 异步模式 |
|
|
120
|
+
| `timeoutMs` | `MEMORY_TIMEOUT_MS` | `5000` | 请求超时时间 (ms) |
|
|
121
|
+
| `retries` | `MEMORY_RETRIES` | `1` | 重试次数 |
|
|
122
|
+
| `throttleMs` | `MEMORY_THROTTLE_MS` | `0` | 节流间隔 (ms) |
|
|
123
|
+
| `addMemoryList` | `MEMORY_ADD_LIST` | `["stream_v2"]` | 要添加的记忆类型 |
|
|
124
|
+
|
|
125
|
+
## 工作流程
|
|
126
|
+
|
|
127
|
+
### 记忆召回 (before_agent_start)
|
|
128
|
+
|
|
129
|
+
1. 用户发送消息
|
|
130
|
+
2. 插件使用消息内容作为查询,调用 `/memory/v2/memory-stream-unified-retrieval`
|
|
131
|
+
3. 检索到的相关记忆被格式化并注入到 Agent 的上下文中
|
|
132
|
+
4. Agent 开始处理用户请求
|
|
133
|
+
|
|
134
|
+
### 记忆存储 (agent_end)
|
|
135
|
+
|
|
136
|
+
1. Agent 完成响应
|
|
137
|
+
2. 插件提取最后一轮对话 (或完整会话)
|
|
138
|
+
3. 调用 `/memory/v2/memory-add` 保存对话
|
|
139
|
+
4. 对话被总结并存储为情景记忆
|
|
140
|
+
|
|
141
|
+
## API 接口
|
|
142
|
+
|
|
143
|
+
本插件调用以下 Memory 服务 API:
|
|
144
|
+
|
|
145
|
+
### 记忆检索
|
|
146
|
+
|
|
147
|
+
```
|
|
148
|
+
POST /memory/v2/memory-stream-unified-retrieval
|
|
149
|
+
Header: system-token: <your-token>
|
|
150
|
+
|
|
151
|
+
{
|
|
152
|
+
"query": "用户的问题",
|
|
153
|
+
"user_id": "user-123",
|
|
154
|
+
"agent_id": "agent-456",
|
|
155
|
+
"limit": 6,
|
|
156
|
+
"min_score": 0.1,
|
|
157
|
+
"is_global_memory": true
|
|
158
|
+
}
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
### 记忆添加
|
|
162
|
+
|
|
163
|
+
```
|
|
164
|
+
POST /memory/v2/memory-add
|
|
165
|
+
Header: system-token: <your-token>
|
|
166
|
+
|
|
167
|
+
{
|
|
168
|
+
"messages": [
|
|
169
|
+
{"role": "user", "content": "..."},
|
|
170
|
+
{"role": "assistant", "content": "..."}
|
|
171
|
+
],
|
|
172
|
+
"session_id": "conversation-123",
|
|
173
|
+
"user_id": "user-123",
|
|
174
|
+
"agent_id": "agent-456",
|
|
175
|
+
"add_memory_list": ["stream_v2"]
|
|
176
|
+
}
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
## 内网/公网部署
|
|
180
|
+
|
|
181
|
+
### 内网用户
|
|
182
|
+
|
|
183
|
+
直接配置内网 API 地址:
|
|
184
|
+
|
|
185
|
+
```bash
|
|
186
|
+
export MEMORY_BASE_URL="http://memory-server.internal:9008"
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
### 公网用户
|
|
190
|
+
|
|
191
|
+
配置公网网关地址:
|
|
192
|
+
|
|
193
|
+
```bash
|
|
194
|
+
export MEMORY_BASE_URL="https://memory-api.your-domain.com"
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
## 许可证
|
|
198
|
+
|
|
199
|
+
Apache-2.0
|
|
200
|
+
|
|
201
|
+
## 贡献
|
|
202
|
+
|
|
203
|
+
欢迎提交 Issue 和 Pull Request!
|
|
204
|
+
|
|
205
|
+
## 联系
|
|
206
|
+
|
|
207
|
+
- 作者: Personal Flow Team
|
package/README_ZH.md
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
# Human-Like Memory Plugin for OpenClaw
|
|
2
|
+
|
|
3
|
+
[English](README.md) | 中文
|
|
4
|
+
|
|
5
|
+
一个用于 OpenClaw 的长期记忆插件,自动在对话前召回相关记忆,并在对话后持久化新记忆。
|
|
6
|
+
|
|
7
|
+
## 功能特性
|
|
8
|
+
|
|
9
|
+
- 🧠 **自动记忆召回**: 在 Agent 开始前自动检索与当前对话相关的历史记忆
|
|
10
|
+
- 💾 **自动记忆存储**: 在对话结束后自动将对话保存为新的记忆
|
|
11
|
+
- 🌍 **全局/会话记忆**: 支持跨会话的全局记忆检索或仅当前会话的记忆
|
|
12
|
+
- ⚙️ **灵活配置**: 支持通过环境变量或配置文件自定义所有参数
|
|
13
|
+
- ⚡ **异步模式**: 支持异步模式,不阻塞对话流程
|
|
14
|
+
|
|
15
|
+
## 快速开始
|
|
16
|
+
|
|
17
|
+
### 1. 安装插件
|
|
18
|
+
|
|
19
|
+
**方式 A: 本地路径安装 (推荐,适合离线环境)**
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
# 将插件文件夹复制到 OpenClaw 扩展目录
|
|
23
|
+
cp -r human-like-mem-openclaw-plugin ~/.openclaw/extensions/
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
**方式 B: 从 Git 仓库安装**
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
npm install git+https://gitlab.ttyuyin.com/personalization_group/human-like-mem-openclaw-plugin.git
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
**方式 C: 从 tarball 安装 (离线环境)**
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
# 将 .tgz 文件拷贝到目标机器
|
|
36
|
+
npm install ./human-like-mem-openclaw-plugin-0.1.0.tgz
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
### 2. 配置环境变量
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
# 添加到 ~/.zshrc 或 ~/.bashrc
|
|
43
|
+
export MEMORY_SYSTEM_TOKEN="your-system-token"
|
|
44
|
+
export MEMORY_BASE_URL="https://your-memory-api.example.com"
|
|
45
|
+
export MEMORY_USER_ID="your-user-id"
|
|
46
|
+
|
|
47
|
+
source ~/.zshrc
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
### 3. 启用插件
|
|
51
|
+
|
|
52
|
+
编辑 `~/.openclaw/openclaw.json`:
|
|
53
|
+
|
|
54
|
+
```json
|
|
55
|
+
{
|
|
56
|
+
"plugins": {
|
|
57
|
+
"entries": {
|
|
58
|
+
"human-like-mem-openclaw-plugin": {
|
|
59
|
+
"enabled": true
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### 4. 重启 OpenClaw
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
openclaw gateway restart
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## 工作原理
|
|
73
|
+
|
|
74
|
+
```
|
|
75
|
+
用户输入
|
|
76
|
+
│
|
|
77
|
+
▼
|
|
78
|
+
┌─────────────────────────────────────┐
|
|
79
|
+
│ before_agent_start │
|
|
80
|
+
│ - 使用用户输入检索相关记忆 │
|
|
81
|
+
│ - 将记忆注入到 Agent 上下文 │
|
|
82
|
+
└─────────────────────────────────────┘
|
|
83
|
+
│
|
|
84
|
+
▼
|
|
85
|
+
┌─────────────────────────────────────┐
|
|
86
|
+
│ Agent 处理 │
|
|
87
|
+
│ - Agent 可以看到历史记忆 │
|
|
88
|
+
│ - Agent 生成响应 │
|
|
89
|
+
└─────────────────────────────────────┘
|
|
90
|
+
│
|
|
91
|
+
▼
|
|
92
|
+
┌─────────────────────────────────────┐
|
|
93
|
+
│ agent_end │
|
|
94
|
+
│ - 提取本轮对话 │
|
|
95
|
+
│ - 异步保存到记忆服务 │
|
|
96
|
+
└─────────────────────────────────────┘
|
|
97
|
+
│
|
|
98
|
+
▼
|
|
99
|
+
用户收到响应
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
## 配置说明
|
|
103
|
+
|
|
104
|
+
### 必需配置
|
|
105
|
+
|
|
106
|
+
| 参数 | 环境变量 | 说明 |
|
|
107
|
+
|------|----------|------|
|
|
108
|
+
| `systemToken` | `MEMORY_SYSTEM_TOKEN` | 系统认证令牌,用于 API 鉴权 |
|
|
109
|
+
| `baseUrl` | `MEMORY_BASE_URL` | Memory 服务的 API 地址 |
|
|
110
|
+
|
|
111
|
+
### 可选配置
|
|
112
|
+
|
|
113
|
+
| 参数 | 环境变量 | 默认值 | 说明 |
|
|
114
|
+
|------|----------|--------|------|
|
|
115
|
+
| `userId` | `MEMORY_USER_ID` | `openclaw-user` | 用户标识 |
|
|
116
|
+
| `agentId` | `MEMORY_AGENT_ID` | `openclaw-agent` | Agent 标识 |
|
|
117
|
+
| `recallEnabled` | `MEMORY_RECALL_ENABLED` | `true` | 是否启用记忆召回 |
|
|
118
|
+
| `addEnabled` | `MEMORY_ADD_ENABLED` | `true` | 是否启用记忆存储 |
|
|
119
|
+
| `recallGlobal` | `MEMORY_RECALL_GLOBAL` | `true` | 是否全局搜索记忆 |
|
|
120
|
+
| `memoryLimitNumber` | `MEMORY_LIMIT_NUMBER` | `6` | 召回记忆的最大数量 |
|
|
121
|
+
| `minScore` | `MEMORY_MIN_SCORE` | `0.1` | 最低相关性分数 (0-1) |
|
|
122
|
+
| `captureStrategy` | `MEMORY_CAPTURE_STRATEGY` | `last_turn` | `last_turn` 或 `full_session` |
|
|
123
|
+
|
|
124
|
+
## 常见问题
|
|
125
|
+
|
|
126
|
+
### Q: 如何获取 System Token?
|
|
127
|
+
|
|
128
|
+
A: 请联系管理员获取系统令牌,或在 Memory 服务管理后台创建。
|
|
129
|
+
|
|
130
|
+
### Q: 为什么记忆没有被召回?
|
|
131
|
+
|
|
132
|
+
A: 检查以下几点:
|
|
133
|
+
1. 确认 `MEMORY_RECALL_ENABLED` 为 `true`
|
|
134
|
+
2. 确认 `MEMORY_SYSTEM_TOKEN` 已正确配置
|
|
135
|
+
3. 确认 Memory 服务可访问
|
|
136
|
+
4. 检查 `min_score` 设置是否过高
|
|
137
|
+
|
|
138
|
+
### Q: 如何只保存记忆不召回?
|
|
139
|
+
|
|
140
|
+
A: 设置 `MEMORY_RECALL_ENABLED=false`
|
|
141
|
+
|
|
142
|
+
### Q: 如何调试插件?
|
|
143
|
+
|
|
144
|
+
A: 查看 OpenClaw 的日志输出,插件会记录详细的调试信息。
|
|
145
|
+
|
|
146
|
+
## 许可证
|
|
147
|
+
|
|
148
|
+
Apache-2.0
|
|
149
|
+
|
|
150
|
+
## 联系我们
|
|
151
|
+
|
|
152
|
+
- 作者: Personal Flow Team
|
package/index.js
ADDED
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AI Social Memory Plugin for OpenClaw
|
|
3
|
+
*
|
|
4
|
+
* A lifecycle plugin that integrates long-term memory capabilities.
|
|
5
|
+
* Automatically recalls relevant memories before agent execution
|
|
6
|
+
* and persists conversations afterward.
|
|
7
|
+
*
|
|
8
|
+
* @author Personal Flow Team <jianghaibo@52tt.com>
|
|
9
|
+
* @license Apache-2.0
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
const USER_QUERY_MARKER = "--- User Query ---";
|
|
13
|
+
|
|
14
|
+
// Session-level conversation counters for unique IDs
|
|
15
|
+
const conversationCounters = new Map();
|
|
16
|
+
|
|
17
|
+
// Throttle state for rate limiting
|
|
18
|
+
let lastAddTime = 0;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Display warning when system token is not configured
|
|
22
|
+
*/
|
|
23
|
+
function warnMissingSystemToken(log, context) {
|
|
24
|
+
const msg = `
|
|
25
|
+
╔════════════════════════════════════════════════════════════════════════════╗
|
|
26
|
+
║ ⚠️ Memory Plugin: MEMORY_SYSTEM_TOKEN not configured ║
|
|
27
|
+
║ ║
|
|
28
|
+
║ Please set your system token: ║
|
|
29
|
+
║ ║
|
|
30
|
+
║ Bash/Zsh: ║
|
|
31
|
+
║ echo 'export MEMORY_SYSTEM_TOKEN="your-token"' >> ~/.zshrc ║
|
|
32
|
+
║ source ~/.zshrc ║
|
|
33
|
+
║ ║
|
|
34
|
+
║ PowerShell: ║
|
|
35
|
+
║ [Environment]::SetEnvironmentVariable("MEMORY_SYSTEM_TOKEN", "your-token",║
|
|
36
|
+
║ "User") ║
|
|
37
|
+
║ ║
|
|
38
|
+
║ Contact your administrator to obtain a system token. ║
|
|
39
|
+
╚════════════════════════════════════════════════════════════════════════════╝
|
|
40
|
+
`;
|
|
41
|
+
if (log?.warn) {
|
|
42
|
+
log.warn(msg);
|
|
43
|
+
} else {
|
|
44
|
+
console.warn(msg);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Strip prepended prompt markers from message content
|
|
50
|
+
*/
|
|
51
|
+
function stripPrependedPrompt(content) {
|
|
52
|
+
if (!content) return content;
|
|
53
|
+
const markerIndex = content.indexOf(USER_QUERY_MARKER);
|
|
54
|
+
if (markerIndex !== -1) {
|
|
55
|
+
return content.substring(markerIndex + USER_QUERY_MARKER.length).trim();
|
|
56
|
+
}
|
|
57
|
+
return content;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Get counter suffix for conversation ID (e.g., "#1", "#2")
|
|
62
|
+
*/
|
|
63
|
+
function getCounterSuffix(sessionKey) {
|
|
64
|
+
const count = conversationCounters.get(sessionKey) || 0;
|
|
65
|
+
return count > 0 ? `#${count}` : "";
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Increment conversation counter for a session
|
|
70
|
+
*/
|
|
71
|
+
function bumpConversationCounter(sessionKey) {
|
|
72
|
+
const current = conversationCounters.get(sessionKey) || 0;
|
|
73
|
+
conversationCounters.set(sessionKey, current + 1);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Generate a unique conversation ID
|
|
78
|
+
*/
|
|
79
|
+
function resolveConversationId(cfg, ctx) {
|
|
80
|
+
const base = ctx.conversationId || ctx.sessionId || `session-${Date.now()}`;
|
|
81
|
+
const prefix = cfg.conversationIdPrefix || "";
|
|
82
|
+
const suffix = cfg.conversationIdSuffix || "";
|
|
83
|
+
const sessionKey = `${prefix}${base}${suffix}`;
|
|
84
|
+
const counterSuffix = getCounterSuffix(sessionKey);
|
|
85
|
+
return `${sessionKey}${counterSuffix}`;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Truncate text to specified maximum length
|
|
90
|
+
*/
|
|
91
|
+
function truncate(text, maxLen) {
|
|
92
|
+
if (!text || text.length <= maxLen) return text;
|
|
93
|
+
return text.substring(0, maxLen - 3) + "...";
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Build payload for memory retrieval API
|
|
98
|
+
*/
|
|
99
|
+
function buildRetrievalPayload(cfg, prompt, ctx) {
|
|
100
|
+
const payload = {
|
|
101
|
+
query: prompt,
|
|
102
|
+
user_id: cfg.userId || ctx.userId || "openclaw-user",
|
|
103
|
+
agent_id: cfg.agentId || ctx.agentId || "openclaw-agent",
|
|
104
|
+
limit: cfg.memoryLimitNumber || 6,
|
|
105
|
+
min_score: cfg.minScore || 0.1,
|
|
106
|
+
scenarios: cfg.scenario ? [cfg.scenario] : [],
|
|
107
|
+
user_ids: [cfg.userId || ctx.userId || "openclaw-user"],
|
|
108
|
+
agent_ids: [cfg.agentId || ctx.agentId || "openclaw-agent"],
|
|
109
|
+
is_global_memory: cfg.recallGlobal !== false,
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
// Add session_id for non-global search
|
|
113
|
+
if (!payload.is_global_memory && ctx.sessionId) {
|
|
114
|
+
payload.session_id = ctx.sessionId;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
return payload;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Build payload for memory add API
|
|
122
|
+
*/
|
|
123
|
+
function buildAddMemoryPayload(cfg, messages, ctx) {
|
|
124
|
+
const conversationId = resolveConversationId(cfg, ctx);
|
|
125
|
+
|
|
126
|
+
return {
|
|
127
|
+
messages: messages.map(m => ({
|
|
128
|
+
role: m.role,
|
|
129
|
+
content: truncate(m.content, cfg.maxMessageChars || 20000),
|
|
130
|
+
created_time: m.createdTime || Date.now(),
|
|
131
|
+
})),
|
|
132
|
+
session_id: conversationId,
|
|
133
|
+
user_id: cfg.userId || ctx.userId || "openclaw-user",
|
|
134
|
+
agent_id: cfg.agentId || ctx.agentId || "openclaw-agent",
|
|
135
|
+
user_ids: [cfg.userId || ctx.userId || "openclaw-user"],
|
|
136
|
+
agent_ids: [cfg.agentId || ctx.agentId || "openclaw-agent"],
|
|
137
|
+
add_memory_list: cfg.addMemoryList || ["stream_v2"],
|
|
138
|
+
scenario: cfg.scenario || "",
|
|
139
|
+
session_end: false,
|
|
140
|
+
episodic_memory_type: cfg.recallGlobal !== false ? "global" : "specific",
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Extract only the last user-assistant exchange
|
|
146
|
+
*/
|
|
147
|
+
function pickLastTurnMessages(messages, cfg) {
|
|
148
|
+
if (!messages || messages.length === 0) return [];
|
|
149
|
+
|
|
150
|
+
const result = [];
|
|
151
|
+
|
|
152
|
+
// Find last user message
|
|
153
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
154
|
+
if (messages[i].role === "user") {
|
|
155
|
+
result.unshift({
|
|
156
|
+
role: "user",
|
|
157
|
+
content: stripPrependedPrompt(messages[i].content),
|
|
158
|
+
createdTime: messages[i].createdTime,
|
|
159
|
+
});
|
|
160
|
+
break;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// Find last assistant message
|
|
165
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
166
|
+
if (messages[i].role === "assistant") {
|
|
167
|
+
result.push({
|
|
168
|
+
role: "assistant",
|
|
169
|
+
content: messages[i].content,
|
|
170
|
+
createdTime: messages[i].createdTime,
|
|
171
|
+
});
|
|
172
|
+
break;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
return result;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Process full session messages
|
|
181
|
+
*/
|
|
182
|
+
function pickFullSessionMessages(messages, cfg) {
|
|
183
|
+
if (!messages || messages.length === 0) return [];
|
|
184
|
+
|
|
185
|
+
return messages.map(m => ({
|
|
186
|
+
role: m.role,
|
|
187
|
+
content: m.role === "user" ? stripPrependedPrompt(m.content) : m.content,
|
|
188
|
+
createdTime: m.createdTime,
|
|
189
|
+
}));
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Make HTTP request with retry logic
|
|
194
|
+
*/
|
|
195
|
+
async function httpRequest(url, options, cfg, log) {
|
|
196
|
+
const timeout = cfg.timeoutMs || 5000;
|
|
197
|
+
const retries = cfg.retries || 1;
|
|
198
|
+
|
|
199
|
+
let lastError;
|
|
200
|
+
|
|
201
|
+
for (let attempt = 0; attempt <= retries; attempt++) {
|
|
202
|
+
try {
|
|
203
|
+
const controller = new AbortController();
|
|
204
|
+
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
|
205
|
+
|
|
206
|
+
const response = await fetch(url, {
|
|
207
|
+
...options,
|
|
208
|
+
signal: controller.signal,
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
clearTimeout(timeoutId);
|
|
212
|
+
|
|
213
|
+
if (!response.ok) {
|
|
214
|
+
const errorText = await response.text();
|
|
215
|
+
throw new Error(`HTTP ${response.status}: ${errorText}`);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
return await response.json();
|
|
219
|
+
} catch (error) {
|
|
220
|
+
lastError = error;
|
|
221
|
+
if (log?.debug) {
|
|
222
|
+
log.debug(`Request attempt ${attempt + 1} failed: ${error.message}`);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// Don't retry on abort (timeout)
|
|
226
|
+
if (error.name === 'AbortError') break;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
throw lastError;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Retrieve memories from the API
|
|
235
|
+
*/
|
|
236
|
+
async function retrievalMemory(prompt, cfg, ctx, log) {
|
|
237
|
+
const baseUrl = cfg.baseUrl || process.env.MEMORY_BASE_URL;
|
|
238
|
+
const systemToken = cfg.systemToken || process.env.MEMORY_SYSTEM_TOKEN;
|
|
239
|
+
|
|
240
|
+
if (!systemToken) {
|
|
241
|
+
warnMissingSystemToken(log, ctx);
|
|
242
|
+
return [];
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const url = `${baseUrl}/memory/v2/memory-stream-unified-retrieval`;
|
|
246
|
+
const payload = buildRetrievalPayload(cfg, prompt, ctx);
|
|
247
|
+
|
|
248
|
+
try {
|
|
249
|
+
const result = await httpRequest(url, {
|
|
250
|
+
method: "POST",
|
|
251
|
+
headers: {
|
|
252
|
+
"Content-Type": "application/json",
|
|
253
|
+
"system-token": systemToken,
|
|
254
|
+
"x-request-id": ctx.requestId || `openclaw-${Date.now()}`,
|
|
255
|
+
},
|
|
256
|
+
body: JSON.stringify(payload),
|
|
257
|
+
}, cfg, log);
|
|
258
|
+
|
|
259
|
+
if (log?.debug) {
|
|
260
|
+
log.debug(`Retrieved ${result.streams?.length || 0} memories`);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
return result.streams || [];
|
|
264
|
+
} catch (error) {
|
|
265
|
+
if (log?.warn) {
|
|
266
|
+
log.warn(`Memory retrieval failed: ${error.message}`);
|
|
267
|
+
}
|
|
268
|
+
return [];
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* Add memories to the API
|
|
274
|
+
*/
|
|
275
|
+
async function addMemory(messages, cfg, ctx, log) {
|
|
276
|
+
const baseUrl = cfg.baseUrl || process.env.MEMORY_BASE_URL;
|
|
277
|
+
const systemToken = cfg.systemToken || process.env.MEMORY_SYSTEM_TOKEN;
|
|
278
|
+
|
|
279
|
+
if (!systemToken) {
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// Throttle check
|
|
284
|
+
const throttleMs = cfg.throttleMs || 0;
|
|
285
|
+
if (throttleMs > 0) {
|
|
286
|
+
const now = Date.now();
|
|
287
|
+
if (now - lastAddTime < throttleMs) {
|
|
288
|
+
if (log?.debug) {
|
|
289
|
+
log.debug(`Memory add throttled, skipping`);
|
|
290
|
+
}
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
lastAddTime = now;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
const url = `${baseUrl}/memory/v2/memory-add`;
|
|
297
|
+
const payload = buildAddMemoryPayload(cfg, messages, ctx);
|
|
298
|
+
|
|
299
|
+
try {
|
|
300
|
+
const result = await httpRequest(url, {
|
|
301
|
+
method: "POST",
|
|
302
|
+
headers: {
|
|
303
|
+
"Content-Type": "application/json",
|
|
304
|
+
"system-token": systemToken,
|
|
305
|
+
"x-request-id": ctx.requestId || `openclaw-${Date.now()}`,
|
|
306
|
+
},
|
|
307
|
+
body: JSON.stringify(payload),
|
|
308
|
+
}, cfg, log);
|
|
309
|
+
|
|
310
|
+
if (log?.debug) {
|
|
311
|
+
log.debug(`Memory added successfully: ${result.streams?.length || 0} streams`);
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
return result;
|
|
315
|
+
} catch (error) {
|
|
316
|
+
if (log?.warn) {
|
|
317
|
+
log.warn(`Memory add failed: ${error.message}`);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* Format memories for injection into context
|
|
324
|
+
*/
|
|
325
|
+
function formatMemoriesForContext(memories) {
|
|
326
|
+
if (!memories || memories.length === 0) return "";
|
|
327
|
+
|
|
328
|
+
const lines = memories.map((m, i) => {
|
|
329
|
+
const date = m.stream_date || m.date || "";
|
|
330
|
+
const desc = m.description || m.event || "";
|
|
331
|
+
const score = m.score ? ` (relevance: ${(m.score * 100).toFixed(1)}%)` : "";
|
|
332
|
+
return `${i + 1}. [${date}] ${desc}${score}`;
|
|
333
|
+
});
|
|
334
|
+
|
|
335
|
+
return `## Relevant Memories\n\n${lines.join("\n")}\n\n${USER_QUERY_MARKER}\n`;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* Main plugin export
|
|
340
|
+
*/
|
|
341
|
+
export default function(config) {
|
|
342
|
+
const cfg = {
|
|
343
|
+
baseUrl: config.baseUrl || process.env.MEMORY_BASE_URL || "https://memory-api.example.com",
|
|
344
|
+
systemToken: config.systemToken || process.env.MEMORY_SYSTEM_TOKEN,
|
|
345
|
+
userId: config.userId || process.env.MEMORY_USER_ID || "openclaw-user",
|
|
346
|
+
agentId: config.agentId || process.env.MEMORY_AGENT_ID || "openclaw-agent",
|
|
347
|
+
recallEnabled: config.recallEnabled !== false,
|
|
348
|
+
addEnabled: config.addEnabled !== false,
|
|
349
|
+
recallGlobal: config.recallGlobal !== false,
|
|
350
|
+
memoryLimitNumber: config.memoryLimitNumber || 6,
|
|
351
|
+
minScore: config.minScore || 0.1,
|
|
352
|
+
scenario: config.scenario || "",
|
|
353
|
+
conversationIdPrefix: config.conversationIdPrefix || "",
|
|
354
|
+
conversationIdSuffix: config.conversationIdSuffix || "",
|
|
355
|
+
captureStrategy: config.captureStrategy || "last_turn",
|
|
356
|
+
maxMessageChars: config.maxMessageChars || 20000,
|
|
357
|
+
asyncMode: config.asyncMode !== false,
|
|
358
|
+
timeoutMs: config.timeoutMs || 5000,
|
|
359
|
+
retries: config.retries ?? 1,
|
|
360
|
+
throttleMs: config.throttleMs || 0,
|
|
361
|
+
addMemoryList: config.addMemoryList || ["stream_v2"],
|
|
362
|
+
};
|
|
363
|
+
|
|
364
|
+
return {
|
|
365
|
+
hooks: {
|
|
366
|
+
/**
|
|
367
|
+
* Before agent start: Recall relevant memories
|
|
368
|
+
*/
|
|
369
|
+
"before_agent_start": async (ctx) => {
|
|
370
|
+
if (!cfg.recallEnabled) return;
|
|
371
|
+
|
|
372
|
+
const log = ctx.log;
|
|
373
|
+
const prompt = ctx.prompt || "";
|
|
374
|
+
|
|
375
|
+
if (!prompt.trim()) {
|
|
376
|
+
if (log?.debug) {
|
|
377
|
+
log.debug("Empty prompt, skipping memory recall");
|
|
378
|
+
}
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
const memories = await retrievalMemory(prompt, cfg, ctx, log);
|
|
383
|
+
|
|
384
|
+
if (memories.length > 0) {
|
|
385
|
+
ctx.prependPrompt = formatMemoriesForContext(memories);
|
|
386
|
+
|
|
387
|
+
if (log?.info) {
|
|
388
|
+
log.info(`Injected ${memories.length} memories into context`);
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
},
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* After agent end: Store conversation to memory
|
|
395
|
+
*/
|
|
396
|
+
"agent_end": async (ctx) => {
|
|
397
|
+
if (!cfg.addEnabled) return;
|
|
398
|
+
|
|
399
|
+
const log = ctx.log;
|
|
400
|
+
const messages = ctx.messages || [];
|
|
401
|
+
|
|
402
|
+
if (messages.length === 0) {
|
|
403
|
+
if (log?.debug) {
|
|
404
|
+
log.debug("No messages to save");
|
|
405
|
+
}
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
// Pick messages based on capture strategy
|
|
410
|
+
const messagesToSave = cfg.captureStrategy === "full_session"
|
|
411
|
+
? pickFullSessionMessages(messages, cfg)
|
|
412
|
+
: pickLastTurnMessages(messages, cfg);
|
|
413
|
+
|
|
414
|
+
if (messagesToSave.length === 0) {
|
|
415
|
+
if (log?.debug) {
|
|
416
|
+
log.debug("No valid messages to save after processing");
|
|
417
|
+
}
|
|
418
|
+
return;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// Run async or sync based on config
|
|
422
|
+
if (cfg.asyncMode) {
|
|
423
|
+
// Fire and forget
|
|
424
|
+
addMemory(messagesToSave, cfg, ctx, log).catch(err => {
|
|
425
|
+
if (log?.warn) {
|
|
426
|
+
log.warn(`Async memory add failed: ${err.message}`);
|
|
427
|
+
}
|
|
428
|
+
});
|
|
429
|
+
} else {
|
|
430
|
+
await addMemory(messagesToSave, cfg, ctx, log);
|
|
431
|
+
}
|
|
432
|
+
},
|
|
433
|
+
},
|
|
434
|
+
};
|
|
435
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://openclaw.io/schemas/plugin.json",
|
|
3
|
+
"id": "human-like-mem-openclaw-plugin",
|
|
4
|
+
"name": "AI Social Memory Plugin",
|
|
5
|
+
"description": "Long-term memory plugin for OpenClaw. Automatically recalls relevant memories before conversations and persists new memories after interactions.",
|
|
6
|
+
"version": "0.1.0",
|
|
7
|
+
"kind": "lifecycle",
|
|
8
|
+
"main": "./index.js",
|
|
9
|
+
"author": {
|
|
10
|
+
"name": "hanlaomo"
|
|
11
|
+
},
|
|
12
|
+
"repository": {
|
|
13
|
+
"type": "git",
|
|
14
|
+
"url": "https://github.com/personalization-group/memory-openclaw-plugin"
|
|
15
|
+
},
|
|
16
|
+
"license": "Apache-2.0",
|
|
17
|
+
"keywords": ["memory", "long-term-memory", "ai-social", "recall", "openclaw"],
|
|
18
|
+
|
|
19
|
+
"config": {
|
|
20
|
+
"baseUrl": {
|
|
21
|
+
"type": "string",
|
|
22
|
+
"description": "Memory service API base URL",
|
|
23
|
+
"default": "https://memory-api.example.com",
|
|
24
|
+
"env": "MEMORY_BASE_URL"
|
|
25
|
+
},
|
|
26
|
+
"systemToken": {
|
|
27
|
+
"type": "string",
|
|
28
|
+
"description": "System token for authentication (required)",
|
|
29
|
+
"env": "MEMORY_SYSTEM_TOKEN",
|
|
30
|
+
"required": true
|
|
31
|
+
},
|
|
32
|
+
"userId": {
|
|
33
|
+
"type": "string",
|
|
34
|
+
"description": "User identifier",
|
|
35
|
+
"default": "openclaw-user",
|
|
36
|
+
"env": "MEMORY_USER_ID"
|
|
37
|
+
},
|
|
38
|
+
"agentId": {
|
|
39
|
+
"type": "string",
|
|
40
|
+
"description": "Agent identifier",
|
|
41
|
+
"default": "openclaw-agent",
|
|
42
|
+
"env": "MEMORY_AGENT_ID"
|
|
43
|
+
},
|
|
44
|
+
"recallEnabled": {
|
|
45
|
+
"type": "boolean",
|
|
46
|
+
"description": "Enable memory recall before agent start",
|
|
47
|
+
"default": true,
|
|
48
|
+
"env": "MEMORY_RECALL_ENABLED"
|
|
49
|
+
},
|
|
50
|
+
"addEnabled": {
|
|
51
|
+
"type": "boolean",
|
|
52
|
+
"description": "Enable memory storage after conversation",
|
|
53
|
+
"default": true,
|
|
54
|
+
"env": "MEMORY_ADD_ENABLED"
|
|
55
|
+
},
|
|
56
|
+
"recallGlobal": {
|
|
57
|
+
"type": "boolean",
|
|
58
|
+
"description": "Search across all conversations (true) or current session only (false)",
|
|
59
|
+
"default": true,
|
|
60
|
+
"env": "MEMORY_RECALL_GLOBAL"
|
|
61
|
+
},
|
|
62
|
+
"memoryLimitNumber": {
|
|
63
|
+
"type": "number",
|
|
64
|
+
"description": "Maximum number of memories to retrieve",
|
|
65
|
+
"default": 6,
|
|
66
|
+
"env": "MEMORY_LIMIT_NUMBER"
|
|
67
|
+
},
|
|
68
|
+
"minScore": {
|
|
69
|
+
"type": "number",
|
|
70
|
+
"description": "Minimum relevance score for retrieved memories (0.0-1.0)",
|
|
71
|
+
"default": 0.1,
|
|
72
|
+
"env": "MEMORY_MIN_SCORE"
|
|
73
|
+
},
|
|
74
|
+
"scenario": {
|
|
75
|
+
"type": "string",
|
|
76
|
+
"description": "Memory scenario/category filter",
|
|
77
|
+
"default": "",
|
|
78
|
+
"env": "MEMORY_SCENARIO"
|
|
79
|
+
},
|
|
80
|
+
"conversationIdPrefix": {
|
|
81
|
+
"type": "string",
|
|
82
|
+
"description": "Prefix for conversation ID",
|
|
83
|
+
"default": "",
|
|
84
|
+
"env": "MEMORY_CONVERSATION_PREFIX"
|
|
85
|
+
},
|
|
86
|
+
"conversationIdSuffix": {
|
|
87
|
+
"type": "string",
|
|
88
|
+
"description": "Suffix for conversation ID",
|
|
89
|
+
"default": "",
|
|
90
|
+
"env": "MEMORY_CONVERSATION_SUFFIX"
|
|
91
|
+
},
|
|
92
|
+
"captureStrategy": {
|
|
93
|
+
"type": "string",
|
|
94
|
+
"description": "Message capture strategy: 'last_turn' or 'full_session'",
|
|
95
|
+
"default": "last_turn",
|
|
96
|
+
"env": "MEMORY_CAPTURE_STRATEGY"
|
|
97
|
+
},
|
|
98
|
+
"maxMessageChars": {
|
|
99
|
+
"type": "number",
|
|
100
|
+
"description": "Maximum characters per message",
|
|
101
|
+
"default": 20000,
|
|
102
|
+
"env": "MEMORY_MAX_MESSAGE_CHARS"
|
|
103
|
+
},
|
|
104
|
+
"asyncMode": {
|
|
105
|
+
"type": "boolean",
|
|
106
|
+
"description": "Run memory operations asynchronously",
|
|
107
|
+
"default": true,
|
|
108
|
+
"env": "MEMORY_ASYNC_MODE"
|
|
109
|
+
},
|
|
110
|
+
"timeoutMs": {
|
|
111
|
+
"type": "number",
|
|
112
|
+
"description": "API request timeout in milliseconds",
|
|
113
|
+
"default": 5000,
|
|
114
|
+
"env": "MEMORY_TIMEOUT_MS"
|
|
115
|
+
},
|
|
116
|
+
"retries": {
|
|
117
|
+
"type": "number",
|
|
118
|
+
"description": "Number of retry attempts on failure",
|
|
119
|
+
"default": 1,
|
|
120
|
+
"env": "MEMORY_RETRIES"
|
|
121
|
+
},
|
|
122
|
+
"throttleMs": {
|
|
123
|
+
"type": "number",
|
|
124
|
+
"description": "Throttle interval for memory add operations",
|
|
125
|
+
"default": 0,
|
|
126
|
+
"env": "MEMORY_THROTTLE_MS"
|
|
127
|
+
},
|
|
128
|
+
"addMemoryList": {
|
|
129
|
+
"type": "array",
|
|
130
|
+
"description": "Types of memory to add: ['stream', 'stream_v2', 'persona', 'persona_v2']",
|
|
131
|
+
"default": ["stream_v2"],
|
|
132
|
+
"env": "MEMORY_ADD_LIST"
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "human-like-mem-openclaw-plugin",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Long-term memory plugin for OpenClaw - AI Social Memory Integration",
|
|
5
|
+
"main": "index.js",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"files": [
|
|
8
|
+
"index.js",
|
|
9
|
+
"openclaw.plugin.json",
|
|
10
|
+
"README.md",
|
|
11
|
+
"README_ZH.md",
|
|
12
|
+
"LICENSE"
|
|
13
|
+
],
|
|
14
|
+
"scripts": {
|
|
15
|
+
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
|
|
16
|
+
"lint": "eslint .",
|
|
17
|
+
"format": "prettier --write ."
|
|
18
|
+
},
|
|
19
|
+
"keywords": [
|
|
20
|
+
"openclaw",
|
|
21
|
+
"openclaw-plugin",
|
|
22
|
+
"plugin",
|
|
23
|
+
"memory",
|
|
24
|
+
"ai",
|
|
25
|
+
"long-term-memory",
|
|
26
|
+
"ai-social",
|
|
27
|
+
"human-like-memory"
|
|
28
|
+
],
|
|
29
|
+
"author": "hanlaomo",
|
|
30
|
+
"license": "Apache-2.0",
|
|
31
|
+
"repository": {
|
|
32
|
+
"type": "git",
|
|
33
|
+
"url": "git+https://gitlab.ttyuyin.com/personalization_group/human-like-mem-openclaw-plugin.git"
|
|
34
|
+
},
|
|
35
|
+
"bugs": {
|
|
36
|
+
"url": "https://gitlab.ttyuyin.com/personalization_group/human-like-mem-openclaw-plugin/-/issues"
|
|
37
|
+
},
|
|
38
|
+
"homepage": "https://gitlab.ttyuyin.com/personalization_group/human-like-mem-openclaw-plugin#readme",
|
|
39
|
+
"engines": {
|
|
40
|
+
"node": ">=18.0.0"
|
|
41
|
+
},
|
|
42
|
+
"devDependencies": {
|
|
43
|
+
"eslint": "^8.57.0",
|
|
44
|
+
"jest": "^29.7.0",
|
|
45
|
+
"prettier": "^3.2.0"
|
|
46
|
+
},
|
|
47
|
+
"publishConfig": {
|
|
48
|
+
"access": "public"
|
|
49
|
+
}
|
|
50
|
+
}
|