@kioku-memory/openclaw 0.0.0-stage → 0.0.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 +202 -0
- package/NOTICE +7 -0
- package/README.md +72 -2
- package/index.js +17 -0
- package/kioku.js +365 -0
- package/lib/api.mjs +35 -0
- package/lib/codex.mjs +309 -0
- package/lib/command.mjs +135 -0
- package/lib/config.mjs +50 -0
- package/lib/doctor.mjs +145 -0
- package/lib/dsh.mjs +75 -0
- package/lib/files.mjs +92 -0
- package/lib/hermes.mjs +261 -0
- package/lib/http.mjs +57 -0
- package/lib/import.mjs +262 -0
- package/lib/kioku.mjs +424 -0
- package/lib/lifecycle.mjs +118 -0
- package/lib/login.mjs +257 -0
- package/lib/mcp.mjs +142 -0
- package/lib/openclaw.mjs +248 -0
- package/lib/pi.mjs +81 -0
- package/lib/platforms.mjs +137 -0
- package/lib/profile.mjs +100 -0
- package/lib/redact.mjs +91 -0
- package/lib/secret.mjs +86 -0
- package/lib/setup.mjs +112 -0
- package/lib/sources.mjs +333 -0
- package/lib/target.mjs +62 -0
- package/lib/text.mjs +14 -0
- package/lib/usage.mjs +2 -0
- package/openclaw.plugin.json +28 -0
- package/package.json +40 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
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.
|
|
202
|
+
|
package/NOTICE
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
kioku-plugins
|
|
2
|
+
Copyright 2026 lonelyman0108
|
|
3
|
+
|
|
4
|
+
This product is licensed under the Apache License, Version 2.0 (see LICENSE).
|
|
5
|
+
|
|
6
|
+
packages/core/lib/command.mjs 里给 cmd.exe 转义参数的规则改写自 cross-spawn
|
|
7
|
+
(https://github.com/moxystudio/node-cross-spawn),MIT License,Copyright (c) 2018 Made With MOXY Lda。
|
package/README.md
CHANGED
|
@@ -1,3 +1,73 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Kioku 的 OpenClaw 插件
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
占用 OpenClaw 的记忆槽位,用 Kioku 做长期记忆:每一轮把启动加载(通用的规则、人格、本应用的记忆与本人的偏好)放在系统提示前面,把召回候选放在这一轮输入前面;每轮结束后把输入与回复交给 Kioku,攒批后写成会话摘要;并提供读写记忆的 `kioku_*` 工具。
|
|
4
|
+
|
|
5
|
+
插件只做转发,提示词和输出格式都由服务端决定,服务端更新后不用重装。
|
|
6
|
+
|
|
7
|
+
## 只在本机入口生效
|
|
8
|
+
|
|
9
|
+
第一版只在 OpenClaw 自己的入口里生效:`openclaw agent`(本机运行或经网关)与过了网关鉴权的 HTTP 接口,这两种实测过;终端界面、控制界面走同一个内部通道,没有逐一实测。从 Telegram、Discord 这类外部渠道来的消息里不注入、不上报、不给工具,心跳、定时任务与子 agent 的运行也一样;认不出来的一律不生效。
|
|
10
|
+
|
|
11
|
+
原因:外部渠道里说话的不一定是应用所有者本人,而访问密钥读得到所有者的记忆。
|
|
12
|
+
|
|
13
|
+
占用槽位之后 OpenClaw 自带的记忆工具(`memory_search` 等)在所有会话里都停用,所以外部渠道来的会话里暂时没有长期记忆。主要在外部渠道里用 OpenClaw 的话,先不要装。
|
|
14
|
+
|
|
15
|
+
## 安装
|
|
16
|
+
|
|
17
|
+
要 OpenClaw 2026.6.35 或更新的版本(更早的没有核对过;核对过 2026.6.35 与 2026.11.3)。
|
|
18
|
+
|
|
19
|
+
先在 Kioku 管理界面的「应用」页建一个运行时是 OpenClaw 的应用,签发访问密钥。然后:
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
# 1. 写下服务地址与访问密钥,允许插件读对话
|
|
23
|
+
npx @kioku-memory/cli setup openclaw --server-url https://kioku.example.com
|
|
24
|
+
|
|
25
|
+
# 2. 装上插件(记忆槽位随之换成 kioku)
|
|
26
|
+
openclaw plugins install npm:@kioku-memory/openclaw
|
|
27
|
+
|
|
28
|
+
# 3. 重启网关
|
|
29
|
+
openclaw gateway restart
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
新一些的 OpenClaw(2026.11.3 上是这样)装第三方插件前要确认它声明的能力:第 2 步提示 `requires capability consent` 时,看过插件要用的能力(记忆槽位、每轮的输入与回复、工具)之后加上 `--accept-capabilities` 再运行一次。
|
|
33
|
+
|
|
34
|
+
第 1 步会提示输入访问密钥(不回显);也可以放在 `KIOKU_API_KEY` 里,或者从标准输入给。提示时直接回车就改用浏览器授权(也可以直接运行 `npx @kioku-memory/cli login openclaw --server-url <地址>`):终端显示一个确认码,在管理界面的确认页输入它、选好空间与权限后确认。
|
|
35
|
+
|
|
36
|
+
用 `npx @kioku-memory/cli doctor openclaw` 检查:地址与访问密钥、访问密钥的权限、插件装了没有、记忆槽位选的是不是 kioku、允不允许插件读对话。
|
|
37
|
+
|
|
38
|
+
换访问密钥或地址时重新运行第 1 步;开着的网关一分钟之内认到新的,不用重启。更新插件用 `openclaw plugins update kioku`。
|
|
39
|
+
|
|
40
|
+
## setup 改了什么
|
|
41
|
+
|
|
42
|
+
- `~/.config/kioku/openclaw.json`(权限 600,位置可以用 `KIOKU_CONFIG_DIR` 改):服务地址与访问密钥。不放进 OpenClaw 的配置,访问密钥也不出现在命令的参数里。旁边的 `openclaw-tools.json` 是工具清单的一份副本,插件登记工具时先用它,每小时向 Kioku 重新取一次。
|
|
43
|
+
- 经 `openclaw config set` 改 OpenClaw 的两项,改完读回来核对:
|
|
44
|
+
- `plugins.entries.kioku.hooks.allowConversationAccess` 设为 `true`:第三方插件默认拿不到每轮的输入与回复,召回与会话摘要都要它。
|
|
45
|
+
- `plugins.slots.memory` 设为 `kioku`:装插件时 OpenClaw 自己会选上,`setup` 只在它被换走之后选回来。
|
|
46
|
+
|
|
47
|
+
`--dry-run` 只看要改什么,`--no-check` 不连 Kioku 核对。`--undo` 删掉那两个文件、去掉允许读对话的那一项,记忆槽位选的还是 kioku 时改回 `memory-core`;插件用 `openclaw plugins uninstall kioku` 卸载。
|
|
48
|
+
|
|
49
|
+
没有 `openclaw` 命令,或者它的配置没改成时,地址与访问密钥照样写下,并列出要自己运行的命令。插件的状态没查出来(`openclaw plugins inspect` 失败)时不当成没装,会说明没查出来。
|
|
50
|
+
|
|
51
|
+
## 工作区里的记忆文件
|
|
52
|
+
|
|
53
|
+
OpenClaw 把工作区的 `MEMORY.md`(有内容时)和 `USER.md` 直接放进提示,这不归记忆槽位管,换了槽位照样在。要让长期记忆只在 Kioku 里:
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
npx @kioku-memory/cli import --from openclaw --platform openclaw --dry-run
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
看过计划后去掉 `--dry-run` 写入,再自己清空 `MEMORY.md`。`memory/` 里按日期的笔记不会自动进提示,迁不迁都行。工作区不在默认位置(`~/.openclaw/workspace`)时用 `--path` 指明。
|
|
60
|
+
|
|
61
|
+
## 和别的平台的差别
|
|
62
|
+
|
|
63
|
+
- 启动加载不存进会话:OpenClaw 每一轮重建系统提示,插件按会话记着取到的启动加载、每一轮都放进去,每小时重新取一次。网关重启后第一轮会再取。
|
|
64
|
+
- 工具由插件登记成 OpenClaw 自己的工具,调用转给 Kioku 的 MCP 端点,不用另配 MCP 服务。名字要在插件的清单里声明,服务端新加的工具要等插件更新才有。
|
|
65
|
+
- 工具只在用户从本机入口发起的那一轮里调得动:同一个会话接着跑心跳这类运行时,模型看得到工具,调用会被拒绝。
|
|
66
|
+
- 上报的是这一轮的输入(含运行中排进来的)与助手正常说完的文字;思考、工具调用、出错或被中止的那一段不上报,没成功的一轮不上报。
|
|
67
|
+
- 没有 `kioku run`。要用凭据,另外装 `npm install -g @kioku-memory/cli`,并设置 `KIOKU_SERVER_URL` 与 `KIOKU_API_KEY`。
|
|
68
|
+
|
|
69
|
+
## 排查
|
|
70
|
+
|
|
71
|
+
插件出错时不挡这一轮,也不往对话里写错误,原因写在网关的日志里(以「Kioku」开头,同一个原因只写一次)。还没配置、配置读不懂、服务地址返回跳转时,日志里会说怎么改;插件不跟着跳转走,访问密钥只发给配置的地址。取启动加载或召回失败之后一分钟内,输入前不再向 Kioku 发请求,免得服务端挂住时每一轮都等满时限。
|
|
72
|
+
|
|
73
|
+
`openclaw plugins inspect kioku` 能看到插件的状态、登记的钩子与工具。装好之后没有生效,多半是网关没有重启。
|
package/index.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// OpenClaw 装载的入口。OpenClaw 会重复装载插件(每次运行、每次重建注册表),状态挂在进程上只建一次:
|
|
2
|
+
// 按会话记着的启动加载、取到的工具清单才不会每一轮都重来
|
|
3
|
+
|
|
4
|
+
import { createKioku } from './kioku.js'
|
|
5
|
+
|
|
6
|
+
const STATE = Symbol.for('kioku.openclaw')
|
|
7
|
+
const kioku = (globalThis[STATE] ??= createKioku())
|
|
8
|
+
|
|
9
|
+
export default {
|
|
10
|
+
id: 'kioku',
|
|
11
|
+
name: 'Kioku',
|
|
12
|
+
description: 'Kioku 长期记忆:启动加载、每轮召回、会话摘要与记忆工具',
|
|
13
|
+
kind: 'memory',
|
|
14
|
+
register(api) {
|
|
15
|
+
kioku.register(api)
|
|
16
|
+
},
|
|
17
|
+
}
|
package/kioku.js
ADDED
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
// OpenClaw 的记忆插件:占记忆槽位(OpenClaw 自带的记忆工具随之停用),把每轮输入、每轮结束转发给 Kioku 的
|
|
2
|
+
// 生命周期端点,并把 Kioku 的工具登记成 OpenClaw 的工具。提示词和格式逻辑都由服务端决定。
|
|
3
|
+
// 只在本机入口来的运行里生效:外部渠道(Telegram 这类)来的消息里不注入、不上报、不给工具,认不出来的一律不生效。
|
|
4
|
+
// 任何失败都不挡这一轮、不往对话里写错误,只在日志里说一次。
|
|
5
|
+
// 服务地址与访问密钥来自 kioku setup openclaw 写下的文件,不放进 OpenClaw 的配置
|
|
6
|
+
|
|
7
|
+
import { failureText, KiokuFailure } from './lib/http.mjs'
|
|
8
|
+
import {
|
|
9
|
+
clip,
|
|
10
|
+
contextOf,
|
|
11
|
+
MAX_PROMPT,
|
|
12
|
+
MAX_REPLY,
|
|
13
|
+
MAX_SESSION_ID,
|
|
14
|
+
Misconfigured,
|
|
15
|
+
postEvent,
|
|
16
|
+
TIMEOUTS,
|
|
17
|
+
} from './lib/lifecycle.mjs'
|
|
18
|
+
import { callTool, listTools, readToolCacheSync, writeToolCache } from './lib/mcp.mjs'
|
|
19
|
+
import { readProfile } from './lib/profile.mjs'
|
|
20
|
+
|
|
21
|
+
const PLATFORM = 'openclaw'
|
|
22
|
+
const SETUP_HINT =
|
|
23
|
+
'运行 kioku setup openclaw 配置(没有 kioku 命令时用 npx @kioku-memory/cli setup openclaw)'
|
|
24
|
+
|
|
25
|
+
// 登记的工具名,要和 openclaw.plugin.json 的 contracts.tools 一致:OpenClaw 只认清单里声明过的
|
|
26
|
+
export const TOOL_NAMES = [
|
|
27
|
+
'kioku_boot',
|
|
28
|
+
'kioku_search',
|
|
29
|
+
'kioku_get',
|
|
30
|
+
'kioku_list',
|
|
31
|
+
'kioku_create',
|
|
32
|
+
'kioku_update',
|
|
33
|
+
'kioku_delete',
|
|
34
|
+
'kioku_move',
|
|
35
|
+
'kioku_credential',
|
|
36
|
+
'kioku_credential_save',
|
|
37
|
+
'kioku_credential_delete',
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
// OpenClaw 自己的入口(命令行、终端界面、控制界面、网关的 HTTP 接口)用的内部通道名,过了网关鉴权的才到得了
|
|
41
|
+
const INTERNAL_CHANNEL = 'webchat'
|
|
42
|
+
// 子 agent、定时任务这类不是用户在对话的会话
|
|
43
|
+
const RESERVED_SESSION = /(^|:)(subagent|cron|acp|hook)(:|$)/
|
|
44
|
+
// 请求失败之后这么久之内,输入前不再发请求:服务端挂住时不让每一轮都等满时限
|
|
45
|
+
const BACKOFF = 60_000
|
|
46
|
+
// 启动加载按会话记着,每一轮都放进系统提示(系统提示每轮重建);隔这么久重新取一次
|
|
47
|
+
const BOOT_TTL = 60 * 60_000
|
|
48
|
+
// 工具清单隔这么久重新取一次
|
|
49
|
+
const TOOLS_TTL = 60 * 60_000
|
|
50
|
+
// 隔这么久重读一次配置文件
|
|
51
|
+
const PROFILE_RETRY = 60_000
|
|
52
|
+
// 记着的会话与运行的个数上限
|
|
53
|
+
const MAX_TRACKED = 200
|
|
54
|
+
// 没有正常说完的助手消息:出错、被中止的那一段不算回复
|
|
55
|
+
const UNFINISHED = new Set(['error', 'aborted'])
|
|
56
|
+
|
|
57
|
+
const internal = (value) => value === undefined || value === null || value === INTERNAL_CHANNEL
|
|
58
|
+
const absent = (value) => value === undefined || value === null || value === ''
|
|
59
|
+
const userSession = (key) => typeof key === 'string' && key && !RESERVED_SESSION.test(key)
|
|
60
|
+
|
|
61
|
+
// 这次运行是不是用户从本机入口发起的。按白名单认:通道的几个字段要么没有、要么是内部通道,没有发送者,
|
|
62
|
+
// 是用户触发的(心跳、定时任务不算)
|
|
63
|
+
export function localRun(ctx) {
|
|
64
|
+
if (ctx?.trigger !== 'user') return false
|
|
65
|
+
if (![ctx.messageProvider, ctx.channel, ctx.channelId, ctx.chatId].every(internal)) return false
|
|
66
|
+
if (!absent(ctx.senderId)) return false
|
|
67
|
+
return userSession(ctx.sessionKey)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// 给不给这次运行工具:通道、发送者、会话的规则和上面一样。工具上下文里没有触发方式,
|
|
71
|
+
// 心跳这类不是用户触发的运行在调用时挡(见 createKioku 里的 approved)
|
|
72
|
+
export function localTools(ctx) {
|
|
73
|
+
if (!ctx || !internal(ctx.messageChannel) || !internal(ctx.deliveryContext?.channel)) return false
|
|
74
|
+
if (!absent(ctx.requesterSenderId)) return false
|
|
75
|
+
return userSession(ctx.sessionKey)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function textsIn(content) {
|
|
79
|
+
if (typeof content === 'string') return [content]
|
|
80
|
+
if (!Array.isArray(content)) return []
|
|
81
|
+
return content
|
|
82
|
+
.filter((block) => block?.type === 'text' && typeof block.text === 'string')
|
|
83
|
+
.map((block) => block.text)
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const finished = (message) => message?.role === 'assistant' && !UNFINISHED.has(message.stopReason)
|
|
87
|
+
|
|
88
|
+
// 这一轮说了什么:{ users, reply }。start 是这一轮开始之前会话里已有的消息数,从它往后都是这一轮的:
|
|
89
|
+
// 开头那条用户消息之后排进来的用户消息进 users,助手正常说完的文字都进 reply。
|
|
90
|
+
// 不知道 start、或者消息比 start 还少(中途压缩过)时,只取最后一条用户消息之后的回复
|
|
91
|
+
export function turnOf(messages, start) {
|
|
92
|
+
if (!Array.isArray(messages)) return { users: [], reply: '' }
|
|
93
|
+
const known = Number.isInteger(start) && start >= 0 && start < messages.length
|
|
94
|
+
const from = known ? start : messages.findLastIndex((message) => message?.role === 'user')
|
|
95
|
+
const turn = messages.slice(Math.max(from, 0))
|
|
96
|
+
const first = turn.findIndex((message) => message?.role === 'user')
|
|
97
|
+
const rest = turn.slice(first + 1)
|
|
98
|
+
return {
|
|
99
|
+
users: rest
|
|
100
|
+
.filter((message) => message?.role === 'user')
|
|
101
|
+
.flatMap((message) => textsIn(message.content)),
|
|
102
|
+
reply: rest
|
|
103
|
+
.filter(finished)
|
|
104
|
+
.flatMap((message) => textsIn(message.content))
|
|
105
|
+
.join('\n')
|
|
106
|
+
.trim(),
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// 超出上限时丢掉最早记下的
|
|
111
|
+
function remember(map, key, value) {
|
|
112
|
+
map.delete(key)
|
|
113
|
+
map.set(key, value)
|
|
114
|
+
if (map.size > MAX_TRACKED) map.delete(map.keys().next().value)
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// env 与 now 可以换掉,给用例用
|
|
118
|
+
export function createKioku({ env = process.env, now = Date.now } = {}) {
|
|
119
|
+
// 地址与访问密钥;problem 是配置用不了的原因
|
|
120
|
+
let profile = null
|
|
121
|
+
let problem = null
|
|
122
|
+
let loading = null
|
|
123
|
+
let retryAt = 0
|
|
124
|
+
// 工具清单:先用本机留的那一份,取到新的再换
|
|
125
|
+
const cached = readToolCacheSync(PLATFORM, env)
|
|
126
|
+
let tools = cached?.tools ?? []
|
|
127
|
+
let toolsUrl = cached?.url ?? null
|
|
128
|
+
// 清单是什么时候取的。本机那份还新的话不重新取:openclaw 的每个命令都会装载一次插件
|
|
129
|
+
let toolsAt = cached && cached.at <= now() ? cached.at : 0
|
|
130
|
+
let refreshing = null
|
|
131
|
+
let logger = null
|
|
132
|
+
// 已经说过的问题,同一个不说第二遍
|
|
133
|
+
const told = new Set()
|
|
134
|
+
// 这个时刻之前,输入前不发请求
|
|
135
|
+
let quietUntil = 0
|
|
136
|
+
// 会话的启动加载:会话 id → { text, at }
|
|
137
|
+
const boots = new Map()
|
|
138
|
+
// 进行中的运行:运行 id → { sessionId, prompt, start }
|
|
139
|
+
const runs = new Map()
|
|
140
|
+
// 正在跑用户从本机入口发起的一轮的会话:会话键 → 运行 id。工具只在这样的运行里调得动
|
|
141
|
+
const approved = new Map()
|
|
142
|
+
|
|
143
|
+
function tell(text) {
|
|
144
|
+
if (told.has(text)) return
|
|
145
|
+
told.add(text)
|
|
146
|
+
try {
|
|
147
|
+
logger?.warn?.(text)
|
|
148
|
+
} catch {
|
|
149
|
+
// 日志写不出来也不影响这一轮
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function configNotice() {
|
|
154
|
+
return problem
|
|
155
|
+
? `Kioku 的配置无法使用,长期记忆不可用:${problem}。${SETUP_HINT}`
|
|
156
|
+
: `Kioku 还没有配置服务地址和访问密钥,长期记忆不可用:${SETUP_HINT}`
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async function load() {
|
|
160
|
+
// 读完之前不再起第二次
|
|
161
|
+
retryAt = Infinity
|
|
162
|
+
const before = profile
|
|
163
|
+
try {
|
|
164
|
+
profile = await readProfile(PLATFORM, env)
|
|
165
|
+
problem = null
|
|
166
|
+
} catch (err) {
|
|
167
|
+
profile = null
|
|
168
|
+
problem = err instanceof KiokuFailure ? err.message : failureText(err)
|
|
169
|
+
}
|
|
170
|
+
// 换了地址或访问密钥:之前的失败不算数了,按会话记着的启动加载也是给上一个访问密钥的
|
|
171
|
+
if (before && (before.url !== profile?.url || before.key !== profile?.key)) {
|
|
172
|
+
quietUntil = 0
|
|
173
|
+
boots.clear()
|
|
174
|
+
told.clear()
|
|
175
|
+
}
|
|
176
|
+
// 本机留的清单是别的地址的、或者现在没有配置:不用它
|
|
177
|
+
if (!profile || toolsUrl !== profile.url) {
|
|
178
|
+
tools = []
|
|
179
|
+
toolsAt = 0
|
|
180
|
+
}
|
|
181
|
+
retryAt = now() + PROFILE_RETRY
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// 等配置读完。隔一阵重读一次文件:网关一直开着,中途配好了、换了访问密钥不用重启也认得到
|
|
185
|
+
function ready() {
|
|
186
|
+
if (!loading || now() >= retryAt) loading = load()
|
|
187
|
+
return loading
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// 取一次工具清单,不等它:取到了换掉内存里的并写回本机。取不到时沿用手上的
|
|
191
|
+
function refreshTools() {
|
|
192
|
+
if (refreshing || !profile || (toolsAt && now() - toolsAt < TOOLS_TTL)) return
|
|
193
|
+
const target = profile
|
|
194
|
+
refreshing = listTools(target)
|
|
195
|
+
.then(async (list) => {
|
|
196
|
+
// 一个工具都没有的回答不当真:手上那份接着用,隔一阵再取
|
|
197
|
+
if (!list.length) throw new KiokuFailure('Kioku 的响应格式不对')
|
|
198
|
+
tools = list
|
|
199
|
+
toolsUrl = target.url
|
|
200
|
+
toolsAt = now()
|
|
201
|
+
await writeToolCache(PLATFORM, { url: target.url, tools: list, at: toolsAt }, env)
|
|
202
|
+
})
|
|
203
|
+
.catch((err) => {
|
|
204
|
+
// 隔一阵再试,不每一轮都试
|
|
205
|
+
toolsAt = now() - TOOLS_TTL + BACKOFF
|
|
206
|
+
tell(`Kioku 的工具清单没有取到(${failureText(err)}),稍后再试`)
|
|
207
|
+
})
|
|
208
|
+
.finally(() => {
|
|
209
|
+
refreshing = null
|
|
210
|
+
})
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// 把一个事件交给服务端,返回要注入的文本(没有时为空字符串);失败时说一次原因,返回 undefined
|
|
214
|
+
async function forward(event, body) {
|
|
215
|
+
try {
|
|
216
|
+
const res = await postEvent(profile.url, profile.key, { event, ...body }, TIMEOUTS[event])
|
|
217
|
+
if (event === 'turn.end') {
|
|
218
|
+
// 响应不用看,但要读掉,连接才还得回去
|
|
219
|
+
await res.body?.cancel().catch(() => {})
|
|
220
|
+
return ''
|
|
221
|
+
}
|
|
222
|
+
return contextOf((await res.json()).hostOutput) ?? ''
|
|
223
|
+
} catch (err) {
|
|
224
|
+
// 上报失败不拦之后的召回:它不在输入前等着,慢一点不碍事
|
|
225
|
+
if (event !== 'turn.end') quietUntil = now() + BACKOFF
|
|
226
|
+
// 服务地址返回跳转多半是地址写错了,说明怎么改;也可能只是一时的(维护页),所以照样隔一阵再试
|
|
227
|
+
if (err instanceof Misconfigured) tell(`Kioku 这次没有生效:${err.message}。${SETUP_HINT}`)
|
|
228
|
+
else tell(`Kioku 这次没有生效(${failureText(err)}),稍后的输入会再试`)
|
|
229
|
+
return undefined
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
async function beforePrompt(event, ctx) {
|
|
234
|
+
const sessionKey = typeof ctx?.sessionKey === 'string' ? ctx.sessionKey : undefined
|
|
235
|
+
if (!localRun(ctx)) {
|
|
236
|
+
// 同一个会话接着跑的不是本机入口来的一轮(心跳、外部渠道并进主会话的私聊):工具收回
|
|
237
|
+
if (sessionKey) approved.delete(sessionKey)
|
|
238
|
+
return undefined
|
|
239
|
+
}
|
|
240
|
+
remember(approved, sessionKey, typeof ctx.runId === 'string' ? ctx.runId : '')
|
|
241
|
+
await ready()
|
|
242
|
+
if (!profile || problem) {
|
|
243
|
+
tell(configNotice())
|
|
244
|
+
return undefined
|
|
245
|
+
}
|
|
246
|
+
refreshTools()
|
|
247
|
+
const prompt = typeof event?.prompt === 'string' ? event.prompt.trim() : ''
|
|
248
|
+
const sessionId =
|
|
249
|
+
typeof ctx.sessionId === 'string' && ctx.sessionId
|
|
250
|
+
? ctx.sessionId.slice(0, MAX_SESSION_ID)
|
|
251
|
+
: undefined
|
|
252
|
+
if (sessionId && typeof ctx.runId === 'string' && ctx.runId) {
|
|
253
|
+
const start = Array.isArray(event?.messages) ? event.messages.length : undefined
|
|
254
|
+
remember(runs, ctx.runId, { sessionId, prompt, start })
|
|
255
|
+
}
|
|
256
|
+
const known = sessionId ? boots.get(sessionId) : undefined
|
|
257
|
+
// 刚失败过:这次不等,手上有启动加载就照旧给
|
|
258
|
+
if (now() < quietUntil) return known?.text ? { prependSystemContext: known.text } : undefined
|
|
259
|
+
|
|
260
|
+
const wantBoot = !known || now() - known.at >= BOOT_TTL
|
|
261
|
+
const session = sessionId ? { sessionId } : {}
|
|
262
|
+
// 两个请求一起发:都在这一轮开始之前等着
|
|
263
|
+
const [boot, recall] = await Promise.all([
|
|
264
|
+
wantBoot ? forward('session.start', session) : undefined,
|
|
265
|
+
prompt
|
|
266
|
+
? forward('prompt.submit', { ...session, prompt: clip(prompt, MAX_PROMPT) })
|
|
267
|
+
: undefined,
|
|
268
|
+
])
|
|
269
|
+
// 取到了(哪怕是空的)就记下;没取到时沿用上一次的,下一轮再取
|
|
270
|
+
if (sessionId && typeof boot === 'string') remember(boots, sessionId, { text: boot, at: now() })
|
|
271
|
+
const bootText = typeof boot === 'string' ? boot : known?.text
|
|
272
|
+
// 只交上下文文本:启动加载放系统提示的前面,召回放这一轮输入的前面
|
|
273
|
+
const result = {}
|
|
274
|
+
if (bootText) result.prependSystemContext = bootText
|
|
275
|
+
if (recall) result.prependContext = recall
|
|
276
|
+
return Object.keys(result).length ? result : undefined
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// 一轮结束:把这一轮交给服务端写会话摘要。等它发完(各有时限):一次性的运行里进程接着就退出了。
|
|
280
|
+
// 没成功的、没有回复的一轮不报:没有可以写进摘要的内容
|
|
281
|
+
async function agentEnd(event, ctx) {
|
|
282
|
+
const runId = typeof ctx?.runId === 'string' ? ctx.runId : undefined
|
|
283
|
+
if (typeof ctx?.sessionKey === 'string' && approved.get(ctx.sessionKey) === (runId ?? '')) {
|
|
284
|
+
approved.delete(ctx.sessionKey)
|
|
285
|
+
}
|
|
286
|
+
const run = runId ? runs.get(runId) : undefined
|
|
287
|
+
if (!run) return
|
|
288
|
+
runs.delete(runId)
|
|
289
|
+
if (!profile || problem || event?.success === false) return
|
|
290
|
+
const { users, reply } = turnOf(event?.messages, run.start)
|
|
291
|
+
// 开头的输入用钩子里拿到的那份,运行中排进来的接在后面
|
|
292
|
+
const user = [run.prompt, ...users].join('\n').trim()
|
|
293
|
+
if (!reply || !user) return
|
|
294
|
+
await forward('turn.end', {
|
|
295
|
+
sessionId: run.sessionId,
|
|
296
|
+
user: clip(user, MAX_PROMPT),
|
|
297
|
+
reply: clip(reply, MAX_REPLY),
|
|
298
|
+
})
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function toTool({ name, description, inputSchema }, sessionKey) {
|
|
302
|
+
return {
|
|
303
|
+
name,
|
|
304
|
+
label: name,
|
|
305
|
+
description,
|
|
306
|
+
parameters: inputSchema,
|
|
307
|
+
async execute(_callId, params, signal) {
|
|
308
|
+
const say = (text) => ({ content: [{ type: 'text', text }] })
|
|
309
|
+
// 这个会话现在跑的不是用户从本机入口发起的一轮(心跳这类):不调
|
|
310
|
+
if (!approved.has(sessionKey)) return say('这次运行里不能用 Kioku 的工具')
|
|
311
|
+
await ready()
|
|
312
|
+
if (!profile || problem) return say(configNotice())
|
|
313
|
+
try {
|
|
314
|
+
const { text, isError } = await callTool(profile, name, params, signal)
|
|
315
|
+
return say(text || (isError ? 'Kioku 的这次调用没有成功' : '(没有内容)'))
|
|
316
|
+
} catch (err) {
|
|
317
|
+
return say(`Kioku 的这次调用没有成功:${failureText(err)}`)
|
|
318
|
+
}
|
|
319
|
+
},
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// 工具工厂是同步的:只能给手上已经有的清单
|
|
324
|
+
function toolsFor(ctx) {
|
|
325
|
+
if (!localTools(ctx)) return null
|
|
326
|
+
// 顺便把配置读上、看清单要不要重新取;都不等
|
|
327
|
+
ready().then(refreshTools, () => {})
|
|
328
|
+
const list = tools.filter((tool) => TOOL_NAMES.includes(tool.name))
|
|
329
|
+
return list.length ? list.map((tool) => toTool(tool, ctx.sessionKey)) : null
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// OpenClaw 每装载一次插件注册表就调一次,同一个进程里会调很多次,openclaw 的每个命令也调:
|
|
333
|
+
// 状态都在外面,这里只挂钩子,不读文件、不发请求
|
|
334
|
+
function register(api) {
|
|
335
|
+
logger = api.logger ?? logger
|
|
336
|
+
try {
|
|
337
|
+
// 占住记忆槽位,自带的记忆插件随之停用;提示段不在这里给,由钩子按会话决定
|
|
338
|
+
api.registerMemoryCapability({})
|
|
339
|
+
} catch {
|
|
340
|
+
// 没被选进记忆槽位时不让登记:钩子与工具照常
|
|
341
|
+
}
|
|
342
|
+
const guarded = (handler) => async (event, ctx) => {
|
|
343
|
+
try {
|
|
344
|
+
return await handler(event, ctx)
|
|
345
|
+
} catch (err) {
|
|
346
|
+
tell(`Kioku 的插件出错了(${failureText(err)}),这一轮没有生效`)
|
|
347
|
+
return undefined
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
api.on('before_prompt_build', guarded(beforePrompt))
|
|
351
|
+
api.on('agent_end', guarded(agentEnd))
|
|
352
|
+
api.registerTool(
|
|
353
|
+
(ctx) => {
|
|
354
|
+
try {
|
|
355
|
+
return toolsFor(ctx)
|
|
356
|
+
} catch {
|
|
357
|
+
return null
|
|
358
|
+
}
|
|
359
|
+
},
|
|
360
|
+
{ names: TOOL_NAMES },
|
|
361
|
+
)
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
return { register, beforePrompt, agentEnd, toolsFor, ready }
|
|
365
|
+
}
|