@memtensor/memos-cloud-openclaw-plugin 0.1.1

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 ADDED
@@ -0,0 +1,201 @@
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 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
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,133 @@
1
+ # MemOS Cloud OpenClaw Plugin (Lifecycle)
2
+
3
+ Official plugin maintained by MemTensor.
4
+
5
+ A minimal OpenClaw lifecycle plugin that **recalls** memories from MemOS Cloud before each run and **adds** new messages to MemOS Cloud after each run.
6
+
7
+ ## Features
8
+ - **Recall**: `before_agent_start` → `/search/memory`
9
+ - **Add**: `agent_end` → `/add/message`
10
+ - Uses **Token** auth (`Authorization: Token <MEMOS_API_KEY>`)
11
+
12
+ ## Install
13
+
14
+ ### Option A — GitHub
15
+ ```bash
16
+ openclaw plugins install github:MemTensor/MemOS-Cloud-OpenClaw-Plugin
17
+ openclaw gateway restart
18
+ ```
19
+ Make sure it’s enabled in `~/.openclaw/openclaw.json`:
20
+ ```json
21
+ {
22
+ "plugins": {
23
+ "entries": {
24
+ "memos-cloud-openclaw-plugin": { "enabled": true }
25
+ }
26
+ }
27
+ }
28
+ ```
29
+
30
+ ### Option B — Local path
31
+ Copy this folder into an OpenClaw plugin path (e.g. `~/.openclaw/extensions/`) or use `plugins.load.paths` to point at it.
32
+
33
+ Example `~/.openclaw/openclaw.json`:
34
+ ```json
35
+ {
36
+ "plugins": {
37
+ "entries": {
38
+ "memos-cloud-openclaw-plugin": { "enabled": true }
39
+ },
40
+ "load": { "paths": ["/path/to/memos-cloud-openclaw-plugin"] }
41
+ }
42
+ }
43
+ ```
44
+ Restart the gateway after config changes.
45
+
46
+ ## Environment Variables
47
+ The plugin tries env files in order (**openclaw → moltbot → clawdbot**). For each key, the first file with a value wins.
48
+ If none of these files exist (or the key is missing), it falls back to the process environment.
49
+
50
+ **Where to configure**
51
+ - Files (priority order):
52
+ - `~/.openclaw/.env`
53
+ - `~/.moltbot/.env`
54
+ - `~/.clawdbot/.env`
55
+ - Each line is `KEY=value`
56
+
57
+ **Quick setup (shell)**
58
+ ```bash
59
+ echo 'export MEMOS_API_KEY="mpg-..."' >> ~/.zshrc
60
+ source ~/.zshrc
61
+ # or
62
+
63
+ echo 'export MEMOS_API_KEY="mpg-..."' >> ~/.bashrc
64
+ source ~/.bashrc
65
+ ```
66
+
67
+ **Quick setup (Windows PowerShell)**
68
+ ```powershell
69
+ [System.Environment]::SetEnvironmentVariable("MEMOS_API_KEY", "mpg-...", "User")
70
+ ```
71
+
72
+ If `MEMOS_API_KEY` is missing, the plugin will warn with setup instructions and the API key URL.
73
+
74
+ **Minimal config**
75
+ ```env
76
+ MEMOS_API_KEY=YOUR_TOKEN
77
+ ```
78
+
79
+ **Optional config**
80
+ - `MEMOS_BASE_URL` (default: `https://memos.memtensor.cn/api/openmem/v1`)
81
+ - `MEMOS_API_KEY` (required; Token auth) — get it at https://memos-dashboard.openmem.net/cn/apikeys/
82
+ - `MEMOS_USER_ID` (optional; default: `openclaw-user`)
83
+ - `MEMOS_CONVERSATION_ID` (optional override)
84
+ - `MEMOS_RECALL_GLOBAL` (default: `true`; when true, search does **not** pass conversation_id)
85
+ - `MEMOS_CONVERSATION_PREFIX` / `MEMOS_CONVERSATION_SUFFIX` (optional)
86
+ - `MEMOS_CONVERSATION_SUFFIX_MODE` (`none` | `counter`, default: `none`)
87
+ - `MEMOS_CONVERSATION_RESET_ON_NEW` (default: `true`, requires hooks.internal.enabled)
88
+
89
+ ## Optional Plugin Config
90
+ In `plugins.entries.memos-cloud-openclaw-plugin.config`:
91
+ ```json
92
+ {
93
+ "baseUrl": "https://memos.memtensor.cn/api/openmem/v1",
94
+ "apiKey": "YOUR_API_KEY",
95
+ "userId": "memos_user_123",
96
+ "conversationId": "openclaw-main",
97
+ "queryPrefix": "important user context preferences decisions ",
98
+ "recallEnabled": true,
99
+ "recallGlobal": true,
100
+ "addEnabled": true,
101
+ "captureStrategy": "last_turn",
102
+ "includeAssistant": true,
103
+ "conversationIdPrefix": "",
104
+ "conversationIdSuffix": "",
105
+ "conversationSuffixMode": "none",
106
+ "resetOnNew": true,
107
+ "knowledgebaseIds": [],
108
+ "memoryLimitNumber": 6,
109
+ "preferenceLimitNumber": 6,
110
+ "includePreference": true,
111
+ "includeToolMemory": false,
112
+ "toolMemoryLimitNumber": 6,
113
+ "tags": ["openclaw"],
114
+ "asyncMode": true
115
+ }
116
+ ```
117
+
118
+ ## How it Works
119
+ - **Recall** (`before_agent_start`)
120
+ - Builds a `/search/memory` request using `user_id`, `query` (= prompt + optional prefix), and optional filters.
121
+ - Default **global recall**: when `recallGlobal=true`, it does **not** pass `conversation_id`.
122
+ - Formats a MemOS prompt (Role/System/Memory/Skill/Protocols) from `/search/memory` results, then injects via `prependContext`.
123
+
124
+ - **Add** (`agent_end`)
125
+ - Builds a `/add/message` request with the **last turn** by default (user + assistant).
126
+ - Sends `messages` with `user_id`, `conversation_id`, and optional `tags/info/agent_id/app_id`.
127
+
128
+ ## Notes
129
+ - `conversation_id` defaults to OpenClaw `sessionKey` (unless `conversationId` is provided). **TODO**: consider binding to OpenClaw `sessionId` directly.
130
+ - Optional **prefix/suffix** via env or config; `conversationSuffixMode=counter` increments on `/new` (requires `hooks.internal.enabled`).
131
+
132
+ ## Acknowledgements
133
+ - Thanks to @anatolykoptev (Contributor) — LinkedIn: https://www.linkedin.com/in/koptev?utm_source=share&utm_campaign=share_via&utm_content=profile&utm_medium=ios_app
package/README_ZH.md ADDED
@@ -0,0 +1,140 @@
1
+ # MemOS Cloud OpenClaw Plugin(Lifecycle 插件)
2
+
3
+ 官方维护:MemTensor。
4
+
5
+ 这是一个最小可用的 OpenClaw lifecycle 插件,功能是:
6
+ - **召回记忆**:在每轮对话前从 MemOS Cloud 检索记忆并注入上下文
7
+ - **添加记忆**:在每轮对话结束后把消息写回 MemOS Cloud
8
+
9
+ ## 功能
10
+ - **Recall**:`before_agent_start` → `/search/memory`
11
+ - **Add**:`agent_end` → `/add/message`
12
+ - 使用 **Token** 认证(`Authorization: Token <MEMOS_API_KEY>`)
13
+
14
+ ## 安装
15
+
16
+ ### 方式 A — GitHub
17
+ ```bash
18
+ openclaw plugins install github:MemTensor/MemOS-Cloud-OpenClaw-Plugin
19
+ openclaw gateway restart
20
+ ```
21
+ 确认 `~/.openclaw/openclaw.json` 中已启用:
22
+ ```json
23
+ {
24
+ "plugins": {
25
+ "entries": {
26
+ "memos-cloud-openclaw-plugin": { "enabled": true }
27
+ }
28
+ }
29
+ }
30
+ ```
31
+
32
+ ### 方式 B — 本地路径
33
+ 把本目录放到 OpenClaw 插件路径(如 `~/.openclaw/extensions/`),或用 `plugins.load.paths` 指向它。
34
+
35
+ 示例 `~/.openclaw/openclaw.json`:
36
+ ```json
37
+ {
38
+ "plugins": {
39
+ "entries": {
40
+ "memos-cloud-openclaw-plugin": { "enabled": true }
41
+ },
42
+ "load": { "paths": ["/path/to/memos-cloud-openclaw-plugin"] }
43
+ }
44
+ }
45
+ ```
46
+ 修改配置后需要重启 gateway。
47
+
48
+ ## 环境变量
49
+ 插件按顺序读取 env 文件(**openclaw → moltbot → clawdbot**),每个键优先使用最先匹配到的值。
50
+ 若三个文件都不存在(或该键未找到),才会回退到进程环境变量。
51
+
52
+ **配置位置**
53
+ - 文件(优先级顺序):
54
+ - `~/.openclaw/.env`
55
+ - `~/.moltbot/.env`
56
+ - `~/.clawdbot/.env`
57
+ - 每行格式:`KEY=value`
58
+
59
+ **快速配置(Shell)**
60
+ ```bash
61
+ echo 'export MEMOS_API_KEY="mpg-..."' >> ~/.zshrc
62
+ source ~/.zshrc
63
+ # 或者
64
+
65
+ echo 'export MEMOS_API_KEY="mpg-..."' >> ~/.bashrc
66
+ source ~/.bashrc
67
+ ```
68
+
69
+ **快速配置(Windows PowerShell)**
70
+ ```powershell
71
+ [System.Environment]::SetEnvironmentVariable("MEMOS_API_KEY", "mpg-...", "User")
72
+ ```
73
+
74
+ 若未读取到 `MEMOS_API_KEY`,插件会提示配置方式并附 API Key 获取地址。
75
+
76
+ **最小配置**
77
+ ```env
78
+ MEMOS_API_KEY=YOUR_TOKEN
79
+ ```
80
+
81
+ **可选配置**
82
+ - `MEMOS_BASE_URL`(默认 `https://memos.memtensor.cn/api/openmem/v1`)
83
+ - `MEMOS_API_KEY`(必填,Token 认证)—— 获取地址:https://memos-dashboard.openmem.net/cn/apikeys/
84
+ - `MEMOS_USER_ID`(可选,默认 `openclaw-user`)
85
+ - `MEMOS_CONVERSATION_ID`(可选覆盖)
86
+ - `MEMOS_RECALL_GLOBAL`(默认 `true`;为 true 时检索不传 conversation_id)
87
+ - `MEMOS_CONVERSATION_PREFIX` / `MEMOS_CONVERSATION_SUFFIX`(可选)
88
+ - `MEMOS_CONVERSATION_SUFFIX_MODE`(`none` | `counter`,默认 `none`)
89
+ - `MEMOS_CONVERSATION_RESET_ON_NEW`(默认 `true`,需 hooks.internal.enabled)
90
+
91
+ ## 可选插件配置
92
+ 在 `plugins.entries.memos-cloud-openclaw-plugin.config` 中设置:
93
+ ```json
94
+ {
95
+ "baseUrl": "https://memos.memtensor.cn/api/openmem/v1",
96
+ "apiKey": "YOUR_API_KEY",
97
+ "userId": "memos_user_123",
98
+ "conversationId": "openclaw-main",
99
+ "queryPrefix": "important user context preferences decisions ",
100
+ "recallEnabled": true,
101
+ "recallGlobal": true,
102
+ "addEnabled": true,
103
+ "captureStrategy": "last_turn",
104
+ "includeAssistant": true,
105
+ "conversationIdPrefix": "",
106
+ "conversationIdSuffix": "",
107
+ "conversationSuffixMode": "none",
108
+ "resetOnNew": true,
109
+ "memoryLimitNumber": 6,
110
+ "preferenceLimitNumber": 6,
111
+ "knowledgebaseIds": [],
112
+ "includePreference": true,
113
+ "includeToolMemory": false,
114
+ "toolMemoryLimitNumber": 6,
115
+ "tags": ["openclaw"],
116
+ "asyncMode": true
117
+ }
118
+ ```
119
+
120
+ ## 工作原理
121
+ ### 1) 召回(before_agent_start)
122
+ - 组装 `/search/memory` 请求
123
+ - `user_id`、`query`(= prompt + 可选前缀)
124
+ - 默认**全局召回**:`recallGlobal=true` 时不传 `conversation_id`
125
+ - 可选 `filter` / `knowledgebase_ids`
126
+ - 使用 `/search/memory` 结果按 MemOS 提示词模板(Role/System/Memory/Skill/Protocols)拼装,并通过 `prependContext` 注入
127
+
128
+ ### 2) 添加(agent_end)
129
+ - 默认只写**最后一轮**(user + assistant)
130
+ - 构造 `/add/message` 请求:
131
+ - `user_id`、`conversation_id`
132
+ - `messages` 列表
133
+ - 可选 `tags / info / agent_id / app_id`
134
+
135
+ ## 说明
136
+ - 未显式指定 `conversation_id` 时,默认使用 OpenClaw `sessionKey`。**TODO**:后续考虑直接绑定 OpenClaw `sessionId`。
137
+ - 可配置前后缀;`conversationSuffixMode=counter` 时会在 `/new` 递增(需 `hooks.internal.enabled`)。
138
+
139
+ ## 致谢
140
+ - 感谢 @anatolykoptev(Contributor)— 领英:https://www.linkedin.com/in/koptev?utm_source=share&utm_campaign=share_via&utm_content=profile&utm_medium=ios_app
@@ -0,0 +1,55 @@
1
+ {
2
+ "id": "memos-cloud-openclaw-plugin",
3
+ "name": "MemOS Cloud OpenClaw Plugin",
4
+ "description": "MemOS Cloud recall + add memory via lifecycle hooks",
5
+ "version": "0.1.1",
6
+ "kind": "lifecycle",
7
+ "main": "./index.js",
8
+ "configSchema": {
9
+ "type": "object",
10
+ "properties": {
11
+ "baseUrl": { "type": "string", "description": "MemOS Cloud base URL" },
12
+ "apiKey": { "type": "string", "description": "MemOS API Key (Token auth; supports ~/.openclaw/.env, ~/.moltbot/.env, ~/.clawdbot/.env; falls back to process env)" },
13
+ "userId": { "type": "string", "description": "MemOS user_id (default: openclaw-user)", "default": "openclaw-user" },
14
+ "conversationId": { "type": "string", "description": "Override conversation_id" },
15
+ "conversationIdPrefix": { "type": "string", "description": "conversation_id prefix" },
16
+ "conversationIdSuffix": { "type": "string", "description": "conversation_id suffix" },
17
+ "conversationSuffixMode": {
18
+ "type": "string",
19
+ "enum": ["none", "counter"],
20
+ "default": "none"
21
+ },
22
+ "resetOnNew": { "type": "boolean", "default": true },
23
+ "queryPrefix": { "type": "string", "description": "Prefix added to search queries" },
24
+ "maxQueryChars": { "type": "integer", "description": "Max chars for search query" },
25
+ "recallEnabled": { "type": "boolean", "default": true },
26
+ "recallGlobal": { "type": "boolean", "default": true },
27
+ "addEnabled": { "type": "boolean", "default": true },
28
+ "captureStrategy": {
29
+ "type": "string",
30
+ "enum": ["last_turn", "full_session"],
31
+ "default": "last_turn"
32
+ },
33
+ "maxMessageChars": { "type": "integer", "description": "Max chars per message when adding", "default": 20000 },
34
+ "includeAssistant": { "type": "boolean", "default": true },
35
+ "memoryLimitNumber": { "type": "integer", "default": 6 },
36
+ "preferenceLimitNumber": { "type": "integer", "default": 6 },
37
+ "includePreference": { "type": "boolean", "default": true },
38
+ "includeToolMemory": { "type": "boolean", "default": false },
39
+ "toolMemoryLimitNumber": { "type": "integer", "default": 6 },
40
+ "filter": { "type": "object", "description": "MemOS search filter" },
41
+ "knowledgebaseIds": { "type": "array", "items": { "type": "string" } },
42
+ "tags": { "type": "array", "items": { "type": "string" } },
43
+ "info": { "type": "object", "additionalProperties": true },
44
+ "agentId": { "type": "string" },
45
+ "appId": { "type": "string" },
46
+ "allowPublic": { "type": "boolean", "default": false },
47
+ "allowKnowledgebaseIds": { "type": "array", "items": { "type": "string" } },
48
+ "asyncMode": { "type": "boolean", "default": true },
49
+ "timeoutMs": { "type": "integer", "default": 5000 },
50
+ "retries": { "type": "integer", "default": 1 },
51
+ "throttleMs": { "type": "integer", "default": 0 }
52
+ },
53
+ "additionalProperties": false
54
+ }
55
+ }
package/index.js ADDED
@@ -0,0 +1,255 @@
1
+ import {
2
+ addMessage,
3
+ buildConfig,
4
+ extractText,
5
+ formatPromptBlock,
6
+ USER_QUERY_MARKER,
7
+ searchMemory,
8
+ } from "./lib/memos-cloud-api.js";
9
+
10
+ let lastCaptureTime = 0;
11
+ const conversationCounters = new Map();
12
+ const API_KEY_HELP_URL = "https://memos-dashboard.openmem.net/cn/apikeys/";
13
+ const ENV_FILE_SEARCH_HINTS = ["~/.openclaw/.env", "~/.moltbot/.env", "~/.clawdbot/.env"];
14
+ const MEMOS_SOURCE = "openclaw";
15
+
16
+ function warnMissingApiKey(log, context) {
17
+ const heading = "[memos-cloud] Missing MEMOS_API_KEY (Token auth)";
18
+ const header = `${heading}${context ? `; ${context} skipped` : ""}. Configure it with:`;
19
+ log.warn?.(
20
+ [
21
+ header,
22
+ "echo 'export MEMOS_API_KEY=\"mpg-...\"' >> ~/.zshrc",
23
+ "source ~/.zshrc",
24
+ "or",
25
+ "echo 'export MEMOS_API_KEY=\"mpg-...\"' >> ~/.bashrc",
26
+ "source ~/.bashrc",
27
+ "or",
28
+ "[System.Environment]::SetEnvironmentVariable(\"MEMOS_API_KEY\", \"mpg-...\", \"User\")",
29
+ `Get API key: ${API_KEY_HELP_URL}`,
30
+ ].join("\n"),
31
+ );
32
+ }
33
+
34
+ function stripPrependedPrompt(content) {
35
+ if (!content) return content;
36
+ const idx = content.lastIndexOf(USER_QUERY_MARKER);
37
+ if (idx === -1) return content;
38
+ return content.slice(idx + USER_QUERY_MARKER.length).trimStart();
39
+ }
40
+
41
+ function getCounterSuffix(sessionKey) {
42
+ if (!sessionKey) return "";
43
+ const current = conversationCounters.get(sessionKey) ?? 0;
44
+ return current > 0 ? `#${current}` : "";
45
+ }
46
+
47
+ function bumpConversationCounter(sessionKey) {
48
+ if (!sessionKey) return;
49
+ const current = conversationCounters.get(sessionKey) ?? 0;
50
+ conversationCounters.set(sessionKey, current + 1);
51
+ }
52
+
53
+ function resolveConversationId(cfg, ctx) {
54
+ if (cfg.conversationId) return cfg.conversationId;
55
+ // TODO: consider binding conversation_id directly to OpenClaw sessionId (prefer ctx.sessionId).
56
+ const base = ctx?.sessionKey || ctx?.sessionId || (ctx?.agentId ? `openclaw:${ctx.agentId}` : "");
57
+ const dynamicSuffix = cfg.conversationSuffixMode === "counter" ? getCounterSuffix(ctx?.sessionKey) : "";
58
+ const prefix = cfg.conversationIdPrefix || "";
59
+ const suffix = cfg.conversationIdSuffix || "";
60
+ if (base) return `${prefix}${base}${dynamicSuffix}${suffix}`;
61
+ return `${prefix}openclaw-${Date.now()}${dynamicSuffix}${suffix}`;
62
+ }
63
+
64
+ function buildSearchPayload(cfg, prompt, ctx) {
65
+ const queryRaw = `${cfg.queryPrefix || ""}${prompt}`;
66
+ const query =
67
+ Number.isFinite(cfg.maxQueryChars) && cfg.maxQueryChars > 0
68
+ ? queryRaw.slice(0, cfg.maxQueryChars)
69
+ : queryRaw;
70
+
71
+ const payload = {
72
+ user_id: cfg.userId,
73
+ query,
74
+ source: MEMOS_SOURCE,
75
+ };
76
+
77
+ if (!cfg.recallGlobal) {
78
+ const conversationId = resolveConversationId(cfg, ctx);
79
+ if (conversationId) payload.conversation_id = conversationId;
80
+ }
81
+
82
+ if (cfg.filter) payload.filter = cfg.filter;
83
+ if (cfg.knowledgebaseIds?.length) payload.knowledgebase_ids = cfg.knowledgebaseIds;
84
+
85
+ payload.memory_limit_number = cfg.memoryLimitNumber;
86
+ payload.include_preference = cfg.includePreference;
87
+ payload.preference_limit_number = cfg.preferenceLimitNumber;
88
+ payload.include_tool_memory = cfg.includeToolMemory;
89
+ payload.tool_memory_limit_number = cfg.toolMemoryLimitNumber;
90
+
91
+ return payload;
92
+ }
93
+
94
+ function buildAddMessagePayload(cfg, messages, ctx) {
95
+ const payload = {
96
+ user_id: cfg.userId,
97
+ conversation_id: resolveConversationId(cfg, ctx),
98
+ messages,
99
+ source: MEMOS_SOURCE,
100
+ };
101
+
102
+ if (cfg.agentId) payload.agent_id = cfg.agentId;
103
+ if (cfg.appId) payload.app_id = cfg.appId;
104
+ if (cfg.tags?.length) payload.tags = cfg.tags;
105
+
106
+ const info = {
107
+ source: "openclaw",
108
+ sessionKey: ctx?.sessionKey,
109
+ agentId: ctx?.agentId,
110
+ ...(cfg.info || {}),
111
+ };
112
+ if (Object.keys(info).length > 0) payload.info = info;
113
+
114
+ payload.allow_public = cfg.allowPublic;
115
+ if (cfg.allowKnowledgebaseIds?.length) payload.allow_knowledgebase_ids = cfg.allowKnowledgebaseIds;
116
+ payload.async_mode = cfg.asyncMode;
117
+
118
+ return payload;
119
+ }
120
+
121
+ function pickLastTurnMessages(messages, cfg) {
122
+ const lastUserIndex = messages
123
+ .map((m, idx) => ({ m, idx }))
124
+ .filter(({ m }) => m?.role === "user")
125
+ .map(({ idx }) => idx)
126
+ .pop();
127
+
128
+ if (lastUserIndex === undefined) return [];
129
+
130
+ const slice = messages.slice(lastUserIndex);
131
+ const results = [];
132
+
133
+ for (const msg of slice) {
134
+ if (!msg || !msg.role) continue;
135
+ if (msg.role === "user") {
136
+ const content = stripPrependedPrompt(extractText(msg.content));
137
+ if (content) results.push({ role: "user", content: truncate(content, cfg.maxMessageChars) });
138
+ continue;
139
+ }
140
+ if (msg.role === "assistant" && cfg.includeAssistant) {
141
+ const content = extractText(msg.content);
142
+ if (content) results.push({ role: "assistant", content: truncate(content, cfg.maxMessageChars) });
143
+ }
144
+ }
145
+
146
+ return results;
147
+ }
148
+
149
+ function pickFullSessionMessages(messages, cfg) {
150
+ const results = [];
151
+ for (const msg of messages) {
152
+ if (!msg || !msg.role) continue;
153
+ if (msg.role === "user") {
154
+ const content = stripPrependedPrompt(extractText(msg.content));
155
+ if (content) results.push({ role: "user", content: truncate(content, cfg.maxMessageChars) });
156
+ }
157
+ if (msg.role === "assistant" && cfg.includeAssistant) {
158
+ const content = extractText(msg.content);
159
+ if (content) results.push({ role: "assistant", content: truncate(content, cfg.maxMessageChars) });
160
+ }
161
+ }
162
+ return results;
163
+ }
164
+
165
+ function truncate(text, maxLen) {
166
+ if (!text) return "";
167
+ if (!maxLen) return text;
168
+ return text.length > maxLen ? `${text.slice(0, maxLen)}...` : text;
169
+ }
170
+
171
+ export default {
172
+ id: "memos-cloud-openclaw-plugin",
173
+ name: "MemOS Cloud OpenClaw Plugin",
174
+ description: "MemOS Cloud recall + add memory via lifecycle hooks",
175
+ kind: "lifecycle",
176
+
177
+ register(api) {
178
+ const cfg = buildConfig(api.pluginConfig);
179
+ const log = api.logger ?? console;
180
+
181
+ if (!cfg.envFileStatus?.found) {
182
+ const searchPaths = cfg.envFileStatus?.searchPaths?.join(", ") ?? ENV_FILE_SEARCH_HINTS.join(", ");
183
+ log.warn?.(`[memos-cloud] No .env found in ${searchPaths}; falling back to process env or plugin config.`);
184
+ }
185
+
186
+ if (cfg.conversationSuffixMode === "counter" && cfg.resetOnNew) {
187
+ if (api.config?.hooks?.internal?.enabled !== true) {
188
+ log.warn?.("[memos-cloud] command:new hook requires hooks.internal.enabled = true");
189
+ }
190
+ api.registerHook(
191
+ ["command:new"],
192
+ (event) => {
193
+ if (event?.type === "command" && event?.action === "new") {
194
+ bumpConversationCounter(event.sessionKey);
195
+ }
196
+ },
197
+ {
198
+ name: "memos-cloud-conversation-new",
199
+ description: "Increment MemOS conversation suffix on /new",
200
+ },
201
+ );
202
+ }
203
+
204
+ api.on("before_agent_start", async (event, ctx) => {
205
+ if (!cfg.recallEnabled) return;
206
+ if (!event?.prompt || event.prompt.length < 3) return;
207
+ if (!cfg.apiKey) {
208
+ warnMissingApiKey(log, "recall");
209
+ return;
210
+ }
211
+
212
+ try {
213
+ const payload = buildSearchPayload(cfg, event.prompt, ctx);
214
+ const result = await searchMemory(cfg, payload);
215
+ const promptBlock = formatPromptBlock(result, { wrapTagBlocks: true });
216
+ if (!promptBlock) return;
217
+
218
+ return {
219
+ prependContext: promptBlock,
220
+ };
221
+ } catch (err) {
222
+ log.warn?.(`[memos-cloud] recall failed: ${String(err)}`);
223
+ }
224
+ });
225
+
226
+ api.on("agent_end", async (event, ctx) => {
227
+ if (!cfg.addEnabled) return;
228
+ if (!event?.success || !event?.messages?.length) return;
229
+ if (!cfg.apiKey) {
230
+ warnMissingApiKey(log, "add");
231
+ return;
232
+ }
233
+
234
+ const now = Date.now();
235
+ if (cfg.throttleMs && now - lastCaptureTime < cfg.throttleMs) {
236
+ return;
237
+ }
238
+ lastCaptureTime = now;
239
+
240
+ try {
241
+ const messages =
242
+ cfg.captureStrategy === "full_session"
243
+ ? pickFullSessionMessages(event.messages, cfg)
244
+ : pickLastTurnMessages(event.messages, cfg);
245
+
246
+ if (!messages.length) return;
247
+
248
+ const payload = buildAddMessagePayload(cfg, messages, ctx);
249
+ await addMessage(cfg, payload);
250
+ } catch (err) {
251
+ log.warn?.(`[memos-cloud] add failed: ${String(err)}`);
252
+ }
253
+ });
254
+ },
255
+ };
@@ -0,0 +1,429 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { homedir } from "node:os";
4
+ import { setTimeout as delay } from "node:timers/promises";
5
+
6
+ const DEFAULT_BASE_URL = "https://memos.memtensor.cn/api/openmem/v1";
7
+ export const USER_QUERY_MARKER = "user\u200b原\u200b始\u200bquery\u200b:\u200b\u200b\u200b\u200b";
8
+ const ENV_SOURCES = [
9
+ { name: "openclaw", path: join(homedir(), ".openclaw", ".env") },
10
+ { name: "moltbot", path: join(homedir(), ".moltbot", ".env") },
11
+ { name: "clawdbot", path: join(homedir(), ".clawdbot", ".env") },
12
+ ];
13
+
14
+ let envFilesLoaded = false;
15
+ const envFileContents = new Map();
16
+ const envFileValues = new Map();
17
+
18
+ function stripQuotes(value) {
19
+ if (!value) return value;
20
+ const trimmed = value.trim();
21
+ if (
22
+ (trimmed.startsWith("\"") && trimmed.endsWith("\"")) ||
23
+ (trimmed.startsWith("'") && trimmed.endsWith("'"))
24
+ ) {
25
+ return trimmed.slice(1, -1);
26
+ }
27
+ return trimmed;
28
+ }
29
+
30
+ function extractResultData(result) {
31
+ if (!result || typeof result !== "object") return null;
32
+ return result.data ?? result.data?.data ?? result.data?.result ?? null;
33
+ }
34
+
35
+ function pad2(value) {
36
+ return String(value).padStart(2, "0");
37
+ }
38
+
39
+ function formatTime(value) {
40
+ if (value === undefined || value === null || value === "") return "";
41
+ if (typeof value === "number") {
42
+ const date = new Date(value);
43
+ if (Number.isNaN(date.getTime())) return "";
44
+ return `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())} ${pad2(
45
+ date.getHours(),
46
+ )}:${pad2(date.getMinutes())}`;
47
+ }
48
+ if (typeof value === "string") {
49
+ const trimmed = value.trim();
50
+ if (!trimmed) return "";
51
+ if (/^\d+$/.test(trimmed)) return formatTime(Number(trimmed));
52
+ return trimmed;
53
+ }
54
+ return "";
55
+ }
56
+
57
+ function parseEnvFile(content) {
58
+ const values = new Map();
59
+ for (const line of content.split(/\r?\n/)) {
60
+ const trimmed = line.trim();
61
+ if (!trimmed || trimmed.startsWith("#")) continue;
62
+ const idx = trimmed.indexOf("=");
63
+ if (idx <= 0) continue;
64
+ const key = trimmed.slice(0, idx).trim();
65
+ const rawValue = trimmed.slice(idx + 1);
66
+ if (!key) continue;
67
+ values.set(key, stripQuotes(rawValue));
68
+ }
69
+ return values;
70
+ }
71
+
72
+ function loadEnvFiles() {
73
+ if (envFilesLoaded) return;
74
+ envFilesLoaded = true;
75
+ for (const source of ENV_SOURCES) {
76
+ try {
77
+ const content = readFileSync(source.path, "utf-8");
78
+ envFileContents.set(source.name, content);
79
+ envFileValues.set(source.name, parseEnvFile(content));
80
+ } catch {
81
+ // ignore missing files
82
+ }
83
+ }
84
+ }
85
+
86
+ function loadEnvFromFiles(name) {
87
+ for (const source of ENV_SOURCES) {
88
+ const values = envFileValues.get(source.name);
89
+ if (!values) continue;
90
+ if (values.has(name)) return values.get(name);
91
+ }
92
+ return undefined;
93
+ }
94
+
95
+ function loadEnvVar(name) {
96
+ loadEnvFiles();
97
+ const fromFiles = loadEnvFromFiles(name);
98
+ if (fromFiles !== undefined) return fromFiles;
99
+ if (envFileContents.size === 0) return process.env[name];
100
+ return undefined;
101
+ }
102
+
103
+ export function getEnvFileStatus() {
104
+ loadEnvFiles();
105
+ const sources = ENV_SOURCES.filter((source) => envFileContents.has(source.name));
106
+ return {
107
+ found: sources.length > 0,
108
+ sources: sources.map((source) => source.name),
109
+ paths: sources.map((source) => source.path),
110
+ searchPaths: ENV_SOURCES.map((source) => source.path),
111
+ };
112
+ }
113
+
114
+ function parseBool(value, fallback) {
115
+ if (value === undefined || value === null || value === "") return fallback;
116
+ if (typeof value === "boolean") return value;
117
+ const normalized = String(value).trim().toLowerCase();
118
+ if (["1", "true", "yes", "y", "on"].includes(normalized)) return true;
119
+ if (["0", "false", "no", "n", "off"].includes(normalized)) return false;
120
+ return fallback;
121
+ }
122
+
123
+ export function buildConfig(pluginConfig = {}) {
124
+ const cfg = pluginConfig ?? {};
125
+
126
+ const baseUrl = cfg.baseUrl || loadEnvVar("MEMOS_BASE_URL") || DEFAULT_BASE_URL;
127
+ const apiKey = cfg.apiKey || loadEnvVar("MEMOS_API_KEY") || "";
128
+ const userId = cfg.userId || loadEnvVar("MEMOS_USER_ID") || "openclaw-user";
129
+ const conversationId = cfg.conversationId || loadEnvVar("MEMOS_CONVERSATION_ID") || "";
130
+
131
+ const recallGlobal = parseBool(
132
+ cfg.recallGlobal,
133
+ parseBool(loadEnvVar("MEMOS_RECALL_GLOBAL"), true),
134
+ );
135
+
136
+ const conversationIdPrefix = cfg.conversationIdPrefix ?? loadEnvVar("MEMOS_CONVERSATION_PREFIX") ?? "";
137
+ const conversationIdSuffix = cfg.conversationIdSuffix ?? loadEnvVar("MEMOS_CONVERSATION_SUFFIX") ?? "";
138
+ const conversationSuffixMode =
139
+ cfg.conversationSuffixMode ?? loadEnvVar("MEMOS_CONVERSATION_SUFFIX_MODE") ?? "none";
140
+ const resetOnNew = parseBool(
141
+ cfg.resetOnNew,
142
+ parseBool(loadEnvVar("MEMOS_CONVERSATION_RESET_ON_NEW"), true),
143
+ );
144
+
145
+ return {
146
+ baseUrl: baseUrl.replace(/\/+$/, ""),
147
+ apiKey,
148
+ userId,
149
+ conversationId,
150
+ conversationIdPrefix,
151
+ conversationIdSuffix,
152
+ conversationSuffixMode,
153
+ recallGlobal,
154
+ resetOnNew,
155
+ envFileStatus: getEnvFileStatus(),
156
+ queryPrefix: cfg.queryPrefix ?? "",
157
+ maxQueryChars: cfg.maxQueryChars ?? 0,
158
+ recallEnabled: cfg.recallEnabled !== false,
159
+ addEnabled: cfg.addEnabled !== false,
160
+ captureStrategy: cfg.captureStrategy ?? "last_turn",
161
+ maxMessageChars: cfg.maxMessageChars ?? 20000,
162
+ includeAssistant: cfg.includeAssistant !== false,
163
+ memoryLimitNumber: cfg.memoryLimitNumber ?? 9,
164
+ preferenceLimitNumber: cfg.preferenceLimitNumber ?? 6,
165
+ includePreference: cfg.includePreference !== false,
166
+ includeToolMemory: cfg.includeToolMemory === true,
167
+ toolMemoryLimitNumber: cfg.toolMemoryLimitNumber ?? 6,
168
+ filter: cfg.filter,
169
+ knowledgebaseIds: cfg.knowledgebaseIds ?? [],
170
+ tags: cfg.tags ?? ["openclaw"],
171
+ info: cfg.info ?? {},
172
+ agentId: cfg.agentId,
173
+ appId: cfg.appId,
174
+ allowPublic: cfg.allowPublic ?? false,
175
+ allowKnowledgebaseIds: cfg.allowKnowledgebaseIds ?? [],
176
+ asyncMode: cfg.asyncMode ?? true,
177
+ timeoutMs: cfg.timeoutMs ?? 5000,
178
+ retries: cfg.retries ?? 1,
179
+ throttleMs: cfg.throttleMs ?? 0,
180
+ };
181
+ }
182
+
183
+ export async function callApi({ baseUrl, apiKey, timeoutMs = 5000, retries = 1 }, path, body) {
184
+ if (!apiKey) {
185
+ throw new Error("Missing MEMOS API key (Token auth)");
186
+ }
187
+
188
+ const headers = {
189
+ "Content-Type": "application/json",
190
+ Authorization: `Token ${apiKey}`,
191
+ };
192
+
193
+ let lastError;
194
+ for (let attempt = 0; attempt <= retries; attempt += 1) {
195
+ try {
196
+ const controller = new AbortController();
197
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
198
+
199
+ const res = await fetch(`${baseUrl}${path}`, {
200
+ method: "POST",
201
+ headers,
202
+ body: JSON.stringify(body),
203
+ signal: controller.signal,
204
+ });
205
+
206
+ clearTimeout(timeoutId);
207
+
208
+ if (!res.ok) {
209
+ throw new Error(`HTTP ${res.status}`);
210
+ }
211
+
212
+ return await res.json();
213
+ } catch (err) {
214
+ lastError = err;
215
+ if (attempt < retries) {
216
+ await delay(100 * (attempt + 1));
217
+ }
218
+ }
219
+ }
220
+
221
+ throw lastError;
222
+ }
223
+
224
+ export async function searchMemory(cfg, payload) {
225
+ return callApi(cfg, "/search/memory", payload);
226
+ }
227
+
228
+ export async function addMessage(cfg, payload) {
229
+ return callApi(cfg, "/add/message", payload);
230
+ }
231
+
232
+ export function extractText(content) {
233
+ if (!content) return "";
234
+ if (typeof content === "string") return content;
235
+ if (Array.isArray(content)) {
236
+ return content
237
+ .filter((block) => block && typeof block === "object" && block.type === "text")
238
+ .map((block) => block.text)
239
+ .join(" ");
240
+ }
241
+ return "";
242
+ }
243
+
244
+ function normalizePreferenceType(value) {
245
+ if (!value) return "";
246
+ const normalized = String(value).trim().toLowerCase();
247
+ if (!normalized) return "";
248
+ if (normalized.includes("explicit")) return "Explicit Preference";
249
+ if (normalized.includes("implicit")) return "Implicit Preference";
250
+ return String(value)
251
+ .replace(/[_-]+/g, " ")
252
+ .replace(/\b\w/g, (ch) => ch.toUpperCase());
253
+ }
254
+
255
+ function sanitizeInlineText(text) {
256
+ if (text === undefined || text === null) return "";
257
+ return String(text).replace(/\r?\n+/g, " ").trim();
258
+ }
259
+
260
+ function formatMemoryLine(item, text, options = {}) {
261
+ const cleaned = sanitizeInlineText(text);
262
+ if (!cleaned) return "";
263
+ const maxChars = options.maxItemChars;
264
+ const truncated = truncate(cleaned, maxChars);
265
+ const time = formatTime(item?.create_time);
266
+ if (time) return ` -[${time}] ${truncated}`;
267
+ return ` - ${truncated}`;
268
+ }
269
+
270
+ function formatPreferenceLine(item, text, options = {}) {
271
+ const cleaned = sanitizeInlineText(text);
272
+ if (!cleaned) return "";
273
+ const maxChars = options.maxItemChars;
274
+ const truncated = truncate(cleaned, maxChars);
275
+ const time = formatTime(item?.create_time);
276
+ const type = normalizePreferenceType(item?.preference_type);
277
+ const typeLabel = type ? ` [${type}]` : "";
278
+ if (time) return ` -[${time}]${typeLabel} ${truncated}`;
279
+ return ` -${typeLabel} ${truncated}`;
280
+ }
281
+
282
+ function wrapCodeBlock(lines, options = {}) {
283
+ if (!options.wrapTagBlocks) return lines;
284
+ return ["```text", ...lines, "```"];
285
+ }
286
+
287
+ function buildPromptFromData(data, options = {}) {
288
+ const now = options.currentTime ?? Date.now();
289
+ const nowText = formatTime(now) || formatTime(Date.now()) || "";
290
+ const memoryList = data?.memory_detail_list ?? [];
291
+ const preferenceList = data?.preference_detail_list ?? [];
292
+
293
+ const memoryLines = memoryList
294
+ .map((item) => {
295
+ const text = item?.memory_value || item?.memory_key || "";
296
+ return formatMemoryLine(item, text, options);
297
+ })
298
+ .filter(Boolean);
299
+
300
+ const preferenceLines = preferenceList
301
+ .map((item) => {
302
+ const text = item?.preference || "";
303
+ return formatPreferenceLine(item, text, options);
304
+ })
305
+ .filter(Boolean);
306
+
307
+ const hasContent = memoryLines.length > 0 || preferenceLines.length > 0;
308
+
309
+ if (!hasContent) return "";
310
+
311
+ const memoriesBlock = [
312
+ "<memories>",
313
+ " <facts>",
314
+ ...memoryLines,
315
+ " </facts>",
316
+ " <preferences>",
317
+ ...preferenceLines,
318
+ " </preferences>",
319
+ "</memories>",
320
+ ];
321
+
322
+ const lines = [
323
+ "# Role",
324
+ "",
325
+ "You are an intelligent assistant with long-term memory capabilities (MemOS Assistant). Your goal is to combine retrieved memory fragments to provide highly personalized, accurate, and logically rigorous responses.",
326
+ "",
327
+ "# System Context",
328
+ "",
329
+ `* Current Time: ${nowText} (Use this as the baseline for freshness checks)`,
330
+ "",
331
+ "# Memory Data",
332
+ "",
333
+ 'Below is the information retrieved by MemOS, categorized into "Facts" and "Preferences".',
334
+ "* **Facts**: May include user attributes, historical conversations, or third-party details.",
335
+ "* **Special Note**: Content tagged with '[assistant观点]' or '[模型总结]' represents **past AI inference**, **not** direct user statements.",
336
+ "* **Preferences**: The user's explicit or implicit requirements on response style, format, or reasoning.",
337
+ "",
338
+ ...wrapCodeBlock(memoriesBlock, options),
339
+ "",
340
+ "# Critical Protocol: Memory Safety",
341
+ "",
342
+ "Retrieved memories may contain **AI speculation**, **irrelevant noise**, or **wrong subject attribution**. You must strictly apply the **Four-Step Verdict**. If any step fails, **discard the memory**:",
343
+ "",
344
+ "1. **Source Verification**:",
345
+ "* **Core**: Distinguish direct user statements from AI inference.",
346
+ "* If a memory has tags like '[assistant观点]' or '[模型总结]', treat it as a **hypothesis**, not a user-grounded fact.",
347
+ "* *Counterexample*: If memory says '[assistant观点] User loves mangoes' but the user never said that, do not assume it as fact.",
348
+ "* **Principle: AI summaries are reference-only and have much lower authority than direct user statements.**",
349
+ "",
350
+ "2. **Attribution Check**:",
351
+ "* Is the subject in memory definitely the user?",
352
+ "* If the memory describes a **third party** (e.g., candidate, interviewee, fictional character, case data), never attribute it to the user.",
353
+ "",
354
+ "3. **Strong Relevance Check**:",
355
+ "* Does the memory directly help answer the current 'Original Query'?",
356
+ "* If it is only a keyword overlap with different context, ignore it.",
357
+ "",
358
+ "4. **Freshness Check**:",
359
+ "* If memory conflicts with the user's latest intent, prioritize the current 'Original Query' as the highest source of truth.",
360
+ "",
361
+ "# Instructions",
362
+ "",
363
+ "1. **Review**: Read '<facts>' first and apply the Four-Step Verdict to remove noise and unreliable AI inference.",
364
+ "2. **Execute**:",
365
+ " - Use only memories that pass filtering as context.",
366
+ " - Strictly follow style requirements from '<preferences>'.",
367
+ "3. **Output**: Answer directly. Never mention internal terms such as \"memory store\", \"retrieval\", or \"AI opinions\".",
368
+ "4. **Attention**: Additional memory context is already provided. Do not read from or write to local `MEMORY.md` or `memory/*` files for reference, as they may be outdated or irrelevant to the current query.",
369
+ USER_QUERY_MARKER,
370
+ ];
371
+
372
+ return lines.join("\n");
373
+ }
374
+
375
+ export function formatContextBlock(result, options = {}) {
376
+ const data = extractResultData(result);
377
+ if (!data) return "";
378
+
379
+ const memoryList = data.memory_detail_list ?? [];
380
+ const prefList = data.preference_detail_list ?? [];
381
+ const toolList = data.tool_memory_detail_list ?? [];
382
+ const preferenceNote = data.preference_note;
383
+
384
+ const lines = [];
385
+ if (memoryList.length > 0) {
386
+ lines.push("Facts:");
387
+ for (const item of memoryList) {
388
+ const text = item?.memory_value || item?.memory_key || "";
389
+ if (!text) continue;
390
+ lines.push(`- ${truncate(text, options.maxItemChars)}`);
391
+ }
392
+ }
393
+
394
+ if (prefList.length > 0) {
395
+ lines.push("Preferences:");
396
+ for (const item of prefList) {
397
+ const pref = item?.preference || "";
398
+ const type = item?.preference_type ? `(${item.preference_type}) ` : "";
399
+ if (!pref) continue;
400
+ lines.push(`- ${type}${truncate(pref, options.maxItemChars)}`);
401
+ }
402
+ }
403
+
404
+ if (toolList.length > 0) {
405
+ lines.push("Tool Memories:");
406
+ for (const item of toolList) {
407
+ const value = item?.tool_value || "";
408
+ if (!value) continue;
409
+ lines.push(`- ${truncate(value, options.maxItemChars)}`);
410
+ }
411
+ }
412
+
413
+ if (preferenceNote) {
414
+ lines.push(`Preference Note: ${truncate(preferenceNote, options.maxItemChars)}`);
415
+ }
416
+
417
+ return lines.length > 0 ? lines.join("\n") : "";
418
+ }
419
+
420
+ export function formatPromptBlock(result, options = {}) {
421
+ const data = extractResultData(result);
422
+ if (!data) return "";
423
+ return buildPromptFromData(data, options);
424
+ }
425
+
426
+ function truncate(text, maxLen) {
427
+ if (!text) return "";
428
+ return text.length > maxLen ? `${text.slice(0, maxLen)}...` : text;
429
+ }
@@ -0,0 +1,55 @@
1
+ {
2
+ "id": "memos-cloud-openclaw-plugin",
3
+ "name": "MemOS Cloud OpenClaw Plugin",
4
+ "description": "MemOS Cloud recall + add memory via lifecycle hooks",
5
+ "version": "0.1.1",
6
+ "kind": "lifecycle",
7
+ "main": "./index.js",
8
+ "configSchema": {
9
+ "type": "object",
10
+ "properties": {
11
+ "baseUrl": { "type": "string", "description": "MemOS Cloud base URL" },
12
+ "apiKey": { "type": "string", "description": "MemOS API Key (Token auth; supports ~/.openclaw/.env, ~/.moltbot/.env, ~/.clawdbot/.env; falls back to process env)" },
13
+ "userId": { "type": "string", "description": "MemOS user_id (default: openclaw-user)", "default": "openclaw-user" },
14
+ "conversationId": { "type": "string", "description": "Override conversation_id" },
15
+ "conversationIdPrefix": { "type": "string", "description": "conversation_id prefix" },
16
+ "conversationIdSuffix": { "type": "string", "description": "conversation_id suffix" },
17
+ "conversationSuffixMode": {
18
+ "type": "string",
19
+ "enum": ["none", "counter"],
20
+ "default": "none"
21
+ },
22
+ "resetOnNew": { "type": "boolean", "default": true },
23
+ "queryPrefix": { "type": "string", "description": "Prefix added to search queries" },
24
+ "maxQueryChars": { "type": "integer", "description": "Max chars for search query" },
25
+ "recallEnabled": { "type": "boolean", "default": true },
26
+ "recallGlobal": { "type": "boolean", "default": true },
27
+ "addEnabled": { "type": "boolean", "default": true },
28
+ "captureStrategy": {
29
+ "type": "string",
30
+ "enum": ["last_turn", "full_session"],
31
+ "default": "last_turn"
32
+ },
33
+ "maxMessageChars": { "type": "integer", "description": "Max chars per message when adding", "default": 20000 },
34
+ "includeAssistant": { "type": "boolean", "default": true },
35
+ "memoryLimitNumber": { "type": "integer", "default": 6 },
36
+ "preferenceLimitNumber": { "type": "integer", "default": 6 },
37
+ "includePreference": { "type": "boolean", "default": true },
38
+ "includeToolMemory": { "type": "boolean", "default": false },
39
+ "toolMemoryLimitNumber": { "type": "integer", "default": 6 },
40
+ "filter": { "type": "object", "description": "MemOS search filter" },
41
+ "knowledgebaseIds": { "type": "array", "items": { "type": "string" } },
42
+ "tags": { "type": "array", "items": { "type": "string" } },
43
+ "info": { "type": "object", "additionalProperties": true },
44
+ "agentId": { "type": "string" },
45
+ "appId": { "type": "string" },
46
+ "allowPublic": { "type": "boolean", "default": false },
47
+ "allowKnowledgebaseIds": { "type": "array", "items": { "type": "string" } },
48
+ "asyncMode": { "type": "boolean", "default": true },
49
+ "timeoutMs": { "type": "integer", "default": 5000 },
50
+ "retries": { "type": "integer", "default": 1 },
51
+ "throttleMs": { "type": "integer", "default": 0 }
52
+ },
53
+ "additionalProperties": false
54
+ }
55
+ }
@@ -0,0 +1,55 @@
1
+ {
2
+ "id": "memos-cloud-openclaw-plugin",
3
+ "name": "MemOS Cloud OpenClaw Plugin",
4
+ "description": "MemOS Cloud recall + add memory via lifecycle hooks",
5
+ "version": "0.1.1",
6
+ "kind": "lifecycle",
7
+ "main": "./index.js",
8
+ "configSchema": {
9
+ "type": "object",
10
+ "properties": {
11
+ "baseUrl": { "type": "string", "description": "MemOS Cloud base URL" },
12
+ "apiKey": { "type": "string", "description": "MemOS API Key (Token auth; supports ~/.openclaw/.env, ~/.moltbot/.env, ~/.clawdbot/.env; falls back to process env)" },
13
+ "userId": { "type": "string", "description": "MemOS user_id (default: openclaw-user)", "default": "openclaw-user" },
14
+ "conversationId": { "type": "string", "description": "Override conversation_id" },
15
+ "conversationIdPrefix": { "type": "string", "description": "conversation_id prefix" },
16
+ "conversationIdSuffix": { "type": "string", "description": "conversation_id suffix" },
17
+ "conversationSuffixMode": {
18
+ "type": "string",
19
+ "enum": ["none", "counter"],
20
+ "default": "none"
21
+ },
22
+ "resetOnNew": { "type": "boolean", "default": true },
23
+ "queryPrefix": { "type": "string", "description": "Prefix added to search queries" },
24
+ "maxQueryChars": { "type": "integer", "description": "Max chars for search query" },
25
+ "recallEnabled": { "type": "boolean", "default": true },
26
+ "recallGlobal": { "type": "boolean", "default": true },
27
+ "addEnabled": { "type": "boolean", "default": true },
28
+ "captureStrategy": {
29
+ "type": "string",
30
+ "enum": ["last_turn", "full_session"],
31
+ "default": "last_turn"
32
+ },
33
+ "maxMessageChars": { "type": "integer", "description": "Max chars per message when adding", "default": 20000 },
34
+ "includeAssistant": { "type": "boolean", "default": true },
35
+ "memoryLimitNumber": { "type": "integer", "default": 6 },
36
+ "preferenceLimitNumber": { "type": "integer", "default": 6 },
37
+ "includePreference": { "type": "boolean", "default": true },
38
+ "includeToolMemory": { "type": "boolean", "default": false },
39
+ "toolMemoryLimitNumber": { "type": "integer", "default": 6 },
40
+ "filter": { "type": "object", "description": "MemOS search filter" },
41
+ "knowledgebaseIds": { "type": "array", "items": { "type": "string" } },
42
+ "tags": { "type": "array", "items": { "type": "string" } },
43
+ "info": { "type": "object", "additionalProperties": true },
44
+ "agentId": { "type": "string" },
45
+ "appId": { "type": "string" },
46
+ "allowPublic": { "type": "boolean", "default": false },
47
+ "allowKnowledgebaseIds": { "type": "array", "items": { "type": "string" } },
48
+ "asyncMode": { "type": "boolean", "default": true },
49
+ "timeoutMs": { "type": "integer", "default": 5000 },
50
+ "retries": { "type": "integer", "default": 1 },
51
+ "throttleMs": { "type": "integer", "default": 0 }
52
+ },
53
+ "additionalProperties": false
54
+ }
55
+ }
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "@memtensor/memos-cloud-openclaw-plugin",
3
+ "version": "0.1.1",
4
+ "description": "OpenClaw lifecycle plugin for MemOS Cloud (add + recall memory)",
5
+ "keywords": [
6
+ "memos",
7
+ "memos-cloud",
8
+ "openclaw",
9
+ "plugin",
10
+ "memory"
11
+ ],
12
+ "homepage": "https://github.com/MemTensor/MemOS-Cloud-OpenClaw-Plugin#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/MemTensor/MemOS-Cloud-OpenClaw-Plugin/issues"
15
+ },
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/MemTensor/MemOS-Cloud-OpenClaw-Plugin.git"
19
+ },
20
+ "type": "module",
21
+ "author": "MemTensor",
22
+ "license": "MIT",
23
+ "openclaw": {
24
+ "extensions": ["./index.js"]
25
+ },
26
+ "clawdbot": {
27
+ "extensions": ["./index.js"]
28
+ },
29
+ "moltbot": {
30
+ "extensions": ["./index.js"]
31
+ }
32
+ }