@kioku-memory/openclaw 0.4.1 → 0.6.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/README.md +8 -8
- package/kioku.js +54 -19
- package/lib/command.mjs +7 -1
- package/lib/config.mjs +3 -9
- package/lib/http.mjs +45 -0
- package/lib/kioku.mjs +6 -1
- package/lib/lifecycle.mjs +40 -5
- package/lib/mcp.mjs +40 -11
- package/lib/profile.mjs +1 -1
- package/lib/run.mjs +65 -31
- package/openclaw.plugin.json +2 -5
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Kioku 的 OpenClaw 插件
|
|
2
2
|
|
|
3
|
-
占用 OpenClaw 的记忆槽位,用 Kioku
|
|
3
|
+
占用 OpenClaw 的记忆槽位,用 Kioku 做长期记忆:每一轮把启动加载(常驻记忆、近期会话摘要、当前项目相关记忆与使用指引)放在系统提示前面,把召回候选放在这一轮输入前面;每轮结束后把输入与回复交给 Kioku,攒批后写成会话摘要;并提供读写记忆与查询可用凭据标识的 `kioku_*` 工具。
|
|
4
4
|
|
|
5
5
|
插件只做转发,提示词和输出格式都由服务端决定,服务端更新后不用重装。
|
|
6
6
|
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
|
|
9
9
|
第一版只在 OpenClaw 自己的入口里生效:`openclaw agent`(本机运行或经网关)与过了网关鉴权的 HTTP 接口,这两种实测过;终端界面、控制界面走同一个内部通道,没有逐一实测。从 Telegram、Discord 这类外部渠道来的消息里不注入、不上报、不给工具,心跳、定时任务与子 agent 的运行也一样;认不出来的一律不生效。
|
|
10
10
|
|
|
11
|
-
|
|
11
|
+
原因:外部渠道里说话的不一定是客户端所有者本人,而访问密钥可读取所有者的记忆。
|
|
12
12
|
|
|
13
13
|
占用槽位之后 OpenClaw 自带的记忆工具(`memory_search` 等)在所有会话里都停用,所以外部渠道来的会话里暂时没有长期记忆。主要在外部渠道里用 OpenClaw 的话,先不要装。
|
|
14
14
|
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
|
|
17
17
|
要 OpenClaw 2026.6.35 或更新的版本(更早的没有核对过;核对过 2026.6.35 与 2026.11.3)。
|
|
18
18
|
|
|
19
|
-
先在 Kioku
|
|
19
|
+
先在 Kioku 管理界面的「设置 → 连接与终端」为 OpenClaw 签发访问密钥(或跳过这一步,直接用下面的浏览器授权)。然后:
|
|
20
20
|
|
|
21
21
|
```bash
|
|
22
22
|
# 1. 写下服务地址与访问密钥,允许插件读对话
|
|
@@ -31,7 +31,7 @@ openclaw gateway restart
|
|
|
31
31
|
|
|
32
32
|
新一些的 OpenClaw(2026.11.3 上是这样)装第三方插件前要确认它声明的能力:第 2 步提示 `requires capability consent` 时,看过插件要用的能力(记忆槽位、每轮的输入与回复、工具)之后加上 `--accept-capabilities` 再运行一次。
|
|
33
33
|
|
|
34
|
-
第 1 步会提示输入访问密钥(不回显);也可以放在 `KIOKU_API_KEY` 里,或者从标准输入给。提示时直接回车就改用浏览器授权(也可以直接运行 `npx @kioku-memory/cli login openclaw --server-url
|
|
34
|
+
第 1 步会提示输入访问密钥(不回显);也可以放在 `KIOKU_API_KEY` 里,或者从标准输入给。提示时直接回车就改用浏览器授权(也可以直接运行 `npx @kioku-memory/cli login openclaw --server-url <地址>`):终端显示一个确认码,在管理界面的确认页输入它、选好环境、场域与权限后确认。
|
|
35
35
|
|
|
36
36
|
用 `npx @kioku-memory/cli doctor openclaw` 检查:地址与访问密钥、访问密钥的权限、插件装了没有、记忆槽位选的是不是 kioku、允不允许插件读对话。
|
|
37
37
|
|
|
@@ -41,7 +41,7 @@ openclaw gateway restart
|
|
|
41
41
|
|
|
42
42
|
- `~/.config/kioku/openclaw.json`(权限 600,位置可以用 `KIOKU_CONFIG_DIR` 改):服务地址与访问密钥。不放进 OpenClaw 的配置,访问密钥也不出现在命令的参数里。旁边的 `openclaw-tools.json` 是工具清单的一份副本,插件登记工具时先用它,每小时向 Kioku 重新取一次。
|
|
43
43
|
- 经 `openclaw config set` 改 OpenClaw 的两项,改完读回来核对:
|
|
44
|
-
- `plugins.entries.kioku.hooks.allowConversationAccess` 设为 `true
|
|
44
|
+
- `plugins.entries.kioku.hooks.allowConversationAccess` 设为 `true`:第三方插件默认无法获取每轮的输入与回复,召回与会话摘要都要它。
|
|
45
45
|
- `plugins.slots.memory` 设为 `kioku`:装插件时 OpenClaw 自己会选上,`setup` 只在它被换走之后选回来。
|
|
46
46
|
|
|
47
47
|
`--dry-run` 只看要改什么,`--no-check` 不连 Kioku 核对。`--undo` 删掉那两个文件、去掉允许读对话的那一项,记忆槽位选的还是 kioku 时改回 `memory-core`;插件用 `openclaw plugins uninstall kioku` 卸载。
|
|
@@ -62,12 +62,12 @@ npx @kioku-memory/cli import --from openclaw --platform openclaw --dry-run
|
|
|
62
62
|
|
|
63
63
|
- 启动加载不存进会话:OpenClaw 每一轮重建系统提示,插件按会话记着取到的启动加载、每一轮都放进去,每小时重新取一次。网关重启后第一轮会再取。
|
|
64
64
|
- 工具由插件登记成 OpenClaw 自己的工具,调用转给 Kioku 的 MCP 端点,不用另配 MCP 服务。新一些的 OpenClaw(2026.11.3 上是这样)不把插件的工具直接交给模型,模型要先用它的 `tool_search` 找;启动加载里的使用指引写着工具的名字(`kioku_get` 这些),按名字找得到。名字要在插件的清单里声明,服务端新加的工具要等插件更新才有。
|
|
65
|
-
-
|
|
65
|
+
- 工具只在用户从本机入口发起的那一轮里调得动:同一个会话接着跑心跳这类运行时,模型可见工具,调用会被拒绝。
|
|
66
66
|
- 上报的是这一轮的输入(含运行中排进来的)与助手正常说完的文字;思考、工具调用、出错或被中止的那一段不上报,没成功的一轮不上报。
|
|
67
67
|
- 没有 `kioku run`。要用凭据,另外装 `npm install -g @kioku-memory/cli`,并设置 `KIOKU_SERVER_URL` 与 `KIOKU_API_KEY`。
|
|
68
68
|
|
|
69
69
|
## 排查
|
|
70
70
|
|
|
71
|
-
插件出错时不挡这一轮,也不往对话里写错误,原因写在网关的日志里(以「Kioku
|
|
71
|
+
插件出错时不挡这一轮,也不往对话里写错误,原因写在网关的日志里(以「Kioku」开头,同一个原因只写一次)。尚未配置、配置无法读取、服务地址返回跳转时,日志里会说怎么改;插件不跟着跳转走,访问密钥只发给配置的地址。取启动加载或召回失败之后一分钟内,输入前不再向 Kioku 发请求,免得服务端挂住时每一轮都等满时限。
|
|
72
72
|
|
|
73
|
-
`openclaw plugins inspect kioku`
|
|
73
|
+
`openclaw plugins inspect kioku` 能看到插件的状态、登记的钩子与工具。装好之后没有生效,多半是网关尚未重启。
|
package/kioku.js
CHANGED
|
@@ -4,15 +4,19 @@
|
|
|
4
4
|
// 任何失败都不挡这一轮、不往对话里写错误,只在日志里说一次。
|
|
5
5
|
// 服务地址与访问密钥来自 kioku setup openclaw 写下的文件,不放进 OpenClaw 的配置
|
|
6
6
|
|
|
7
|
+
import { createHash } from 'node:crypto'
|
|
8
|
+
|
|
7
9
|
import { failureText, KiokuFailure } from './lib/http.mjs'
|
|
8
10
|
import {
|
|
9
11
|
clip,
|
|
10
12
|
contextOf,
|
|
13
|
+
deviceKeyOf,
|
|
11
14
|
MAX_PROMPT,
|
|
12
15
|
MAX_REPLY,
|
|
13
16
|
MAX_SESSION_ID,
|
|
14
17
|
Misconfigured,
|
|
15
18
|
postEvent,
|
|
19
|
+
projectOfAsync,
|
|
16
20
|
TIMEOUTS,
|
|
17
21
|
} from './lib/lifecycle.mjs'
|
|
18
22
|
import { callTool, listTools, readToolCacheSync, writeToolCache } from './lib/mcp.mjs'
|
|
@@ -27,14 +31,11 @@ export const TOOL_NAMES = [
|
|
|
27
31
|
'kioku_boot',
|
|
28
32
|
'kioku_search',
|
|
29
33
|
'kioku_get',
|
|
30
|
-
'
|
|
34
|
+
'kioku_browse',
|
|
31
35
|
'kioku_create',
|
|
32
36
|
'kioku_update',
|
|
33
37
|
'kioku_delete',
|
|
34
|
-
'
|
|
35
|
-
'kioku_credential',
|
|
36
|
-
'kioku_credential_save',
|
|
37
|
-
'kioku_credential_delete',
|
|
38
|
+
'kioku_list_credentials',
|
|
38
39
|
]
|
|
39
40
|
|
|
40
41
|
// OpenClaw 自己的入口(命令行、终端界面、控制界面、网关的 HTTP 接口)用的内部通道名,过了网关鉴权的才到得了
|
|
@@ -121,10 +122,12 @@ export function createKioku({ env = process.env, now = Date.now } = {}) {
|
|
|
121
122
|
let problem = null
|
|
122
123
|
let loading = null
|
|
123
124
|
let retryAt = 0
|
|
125
|
+
const keyHashOf = (key) => createHash('sha256').update(key).digest('hex').slice(0, 12)
|
|
124
126
|
// 工具清单:先用本机留的那一份,取到新的再换
|
|
125
127
|
const cached = readToolCacheSync(PLATFORM, env)
|
|
126
128
|
let tools = cached?.tools ?? []
|
|
127
129
|
let toolsUrl = cached?.url ?? null
|
|
130
|
+
let toolsKeyHash = cached?.keyHash ?? null
|
|
128
131
|
// 清单是什么时候取的。本机那份还新的话不重新取:openclaw 的每个命令都会装载一次插件
|
|
129
132
|
let toolsAt = cached && cached.at <= now() ? cached.at : 0
|
|
130
133
|
let refreshing = null
|
|
@@ -135,8 +138,10 @@ export function createKioku({ env = process.env, now = Date.now } = {}) {
|
|
|
135
138
|
let quietUntil = 0
|
|
136
139
|
// 会话的启动加载:会话 id → { text, at }
|
|
137
140
|
const boots = new Map()
|
|
138
|
-
// 进行中的运行:运行 id → { sessionId, prompt, start }
|
|
141
|
+
// 进行中的运行:运行 id → { sessionId, prompt, start, project }
|
|
139
142
|
const runs = new Map()
|
|
143
|
+
// 项目的目录名与仓库名,按目录记着
|
|
144
|
+
const projects = new Map()
|
|
140
145
|
// 正在跑用户从本机入口发起的一轮的会话:会话键 → 运行 id。工具只在这样的运行里调得动
|
|
141
146
|
const approved = new Map()
|
|
142
147
|
// 在后台跑、谁也不等的事:工具工厂里读配置,取工具清单并写回本机
|
|
@@ -169,7 +174,12 @@ export function createKioku({ env = process.env, now = Date.now } = {}) {
|
|
|
169
174
|
function configNotice() {
|
|
170
175
|
return problem
|
|
171
176
|
? `Kioku 的配置无法使用,长期记忆不可用:${problem}。${SETUP_HINT}`
|
|
172
|
-
: `Kioku
|
|
177
|
+
: `Kioku 尚未配置服务地址和访问密钥,长期记忆不可用:${SETUP_HINT}`
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function projectFor(cwd) {
|
|
181
|
+
if (!projects.has(cwd)) projects.set(cwd, projectOfAsync(cwd))
|
|
182
|
+
return projects.get(cwd)
|
|
173
183
|
}
|
|
174
184
|
|
|
175
185
|
async function load() {
|
|
@@ -189,9 +199,17 @@ export function createKioku({ env = process.env, now = Date.now } = {}) {
|
|
|
189
199
|
boots.clear()
|
|
190
200
|
told.clear()
|
|
191
201
|
}
|
|
192
|
-
//
|
|
193
|
-
|
|
202
|
+
// 本机留的清单是别的地址或旧访问密钥的、或者现在没有配置:不用它
|
|
203
|
+
const currentHash = profile ? keyHashOf(profile.key) : null
|
|
204
|
+
if (
|
|
205
|
+
!profile ||
|
|
206
|
+
toolsUrl !== profile.url ||
|
|
207
|
+
(toolsKeyHash && toolsKeyHash !== currentHash) ||
|
|
208
|
+
(before && before.key !== profile.key)
|
|
209
|
+
) {
|
|
194
210
|
tools = []
|
|
211
|
+
toolsUrl = null
|
|
212
|
+
toolsKeyHash = null
|
|
195
213
|
toolsAt = 0
|
|
196
214
|
}
|
|
197
215
|
retryAt = now() + PROFILE_RETRY
|
|
@@ -211,10 +229,12 @@ export function createKioku({ env = process.env, now = Date.now } = {}) {
|
|
|
211
229
|
.then(async (list) => {
|
|
212
230
|
// 一个工具都没有的回答不当真:手上那份接着用,隔一阵再取
|
|
213
231
|
if (!list.length) throw new KiokuFailure('Kioku 的响应格式不对')
|
|
232
|
+
const keyHash = keyHashOf(target.key)
|
|
214
233
|
tools = list
|
|
215
234
|
toolsUrl = target.url
|
|
235
|
+
toolsKeyHash = keyHash
|
|
216
236
|
toolsAt = now()
|
|
217
|
-
await writeToolCache(PLATFORM, { url: target.url, tools: list, at: toolsAt }, env)
|
|
237
|
+
await writeToolCache(PLATFORM, { url: target.url, keyHash, tools: list, at: toolsAt }, env)
|
|
218
238
|
})
|
|
219
239
|
.catch((err) => {
|
|
220
240
|
// 隔一阵再试,不每一轮都试
|
|
@@ -227,10 +247,12 @@ export function createKioku({ env = process.env, now = Date.now } = {}) {
|
|
|
227
247
|
detach(refreshing)
|
|
228
248
|
}
|
|
229
249
|
|
|
250
|
+
const deviceKey = deviceKeyOf(env)
|
|
230
251
|
// 把一个事件交给服务端,返回要注入的文本(没有时为空字符串);失败时说一次原因,返回 undefined
|
|
231
252
|
async function forward(event, body) {
|
|
232
253
|
try {
|
|
233
|
-
const
|
|
254
|
+
const payload = { event, ...(deviceKey ? { deviceKey } : {}), ...body }
|
|
255
|
+
const res = await postEvent(profile.url, profile.key, payload, TIMEOUTS[event])
|
|
234
256
|
if (event === 'turn.end') {
|
|
235
257
|
// 响应不用看,但要读掉,连接才还得回去
|
|
236
258
|
await res.body?.cancel().catch(() => {})
|
|
@@ -241,8 +263,9 @@ export function createKioku({ env = process.env, now = Date.now } = {}) {
|
|
|
241
263
|
// 上报失败不拦之后的召回:它不在输入前等着,慢一点不碍事
|
|
242
264
|
if (event !== 'turn.end') quietUntil = now() + BACKOFF
|
|
243
265
|
// 服务地址返回跳转多半是地址写错了,说明怎么改;也可能只是一时的(维护页),所以照样隔一阵再试
|
|
244
|
-
if (err instanceof Misconfigured)
|
|
245
|
-
|
|
266
|
+
if (err instanceof Misconfigured) {
|
|
267
|
+
tell(`Kioku 这次没有生效:${err.message}。${SETUP_HINT}`)
|
|
268
|
+
} else tell(`Kioku 这次没有生效(${failureText(err)}),稍后的输入会再试`)
|
|
246
269
|
return undefined
|
|
247
270
|
}
|
|
248
271
|
}
|
|
@@ -261,21 +284,29 @@ export function createKioku({ env = process.env, now = Date.now } = {}) {
|
|
|
261
284
|
return undefined
|
|
262
285
|
}
|
|
263
286
|
refreshTools()
|
|
287
|
+
const cwd =
|
|
288
|
+
(typeof ctx?.workspaceDir === 'string' && ctx.workspaceDir) ||
|
|
289
|
+
(typeof ctx?.cwd === 'string' && ctx.cwd) ||
|
|
290
|
+
process.cwd()
|
|
291
|
+
const project = await projectFor(cwd)
|
|
264
292
|
const prompt = typeof event?.prompt === 'string' ? event.prompt.trim() : ''
|
|
265
293
|
const sessionId =
|
|
266
294
|
typeof ctx.sessionId === 'string' && ctx.sessionId
|
|
267
|
-
? ctx.sessionId
|
|
295
|
+
? clip(ctx.sessionId, MAX_SESSION_ID)
|
|
268
296
|
: undefined
|
|
269
297
|
if (sessionId && typeof ctx.runId === 'string' && ctx.runId) {
|
|
270
298
|
const start = Array.isArray(event?.messages) ? event.messages.length : undefined
|
|
271
|
-
remember(runs, ctx.runId, { sessionId, prompt, start })
|
|
299
|
+
remember(runs, ctx.runId, { sessionId, prompt, start, project })
|
|
272
300
|
}
|
|
273
301
|
const known = sessionId ? boots.get(sessionId) : undefined
|
|
274
302
|
// 刚失败过:这次不等,手上有启动加载就照旧给
|
|
275
303
|
if (now() < quietUntil) return known?.text ? { prependSystemContext: known.text } : undefined
|
|
276
304
|
|
|
277
305
|
const wantBoot = !known || now() - known.at >= BOOT_TTL
|
|
278
|
-
const session =
|
|
306
|
+
const session = {
|
|
307
|
+
...(sessionId ? { sessionId } : {}),
|
|
308
|
+
...(Object.keys(project).length ? { project } : {}),
|
|
309
|
+
}
|
|
279
310
|
// 两个请求一起发:都在这一轮开始之前等着
|
|
280
311
|
const [boot, recall] = await Promise.all([
|
|
281
312
|
wantBoot ? forward('session.start', session) : undefined,
|
|
@@ -310,6 +341,7 @@ export function createKioku({ env = process.env, now = Date.now } = {}) {
|
|
|
310
341
|
if (!reply || !user) return
|
|
311
342
|
await forward('turn.end', {
|
|
312
343
|
sessionId: run.sessionId,
|
|
344
|
+
...(Object.keys(run.project ?? {}).length ? { project: run.project } : {}),
|
|
313
345
|
user: clip(user, MAX_PROMPT),
|
|
314
346
|
reply: clip(reply, MAX_REPLY),
|
|
315
347
|
})
|
|
@@ -322,16 +354,19 @@ export function createKioku({ env = process.env, now = Date.now } = {}) {
|
|
|
322
354
|
description,
|
|
323
355
|
parameters: inputSchema,
|
|
324
356
|
async execute(_callId, params, signal) {
|
|
325
|
-
const say = (text) => ({
|
|
357
|
+
const say = (text, isError = false) => ({
|
|
358
|
+
content: [{ type: 'text', text }],
|
|
359
|
+
...(isError ? { isError: true } : {}),
|
|
360
|
+
})
|
|
326
361
|
// 这个会话现在跑的不是用户从本机入口发起的一轮(心跳这类):不调
|
|
327
362
|
if (!approved.has(sessionKey)) return say('这次运行里不能用 Kioku 的工具')
|
|
328
363
|
await ready()
|
|
329
364
|
if (!profile || problem) return say(configNotice())
|
|
330
365
|
try {
|
|
331
366
|
const { text, isError } = await callTool(profile, name, params, signal)
|
|
332
|
-
return say(text || (isError ? 'Kioku
|
|
367
|
+
return say(text || (isError ? 'Kioku 的这次调用失败' : '(没有内容)'), isError)
|
|
333
368
|
} catch (err) {
|
|
334
|
-
return say(`Kioku
|
|
369
|
+
return say(`Kioku 的这次调用失败:${failureText(err)}`, true)
|
|
335
370
|
}
|
|
336
371
|
},
|
|
337
372
|
}
|
package/lib/command.mjs
CHANGED
|
@@ -10,9 +10,15 @@ import { join, win32 } from 'node:path'
|
|
|
10
10
|
|
|
11
11
|
import { KiokuFailure } from './http.mjs'
|
|
12
12
|
|
|
13
|
+
const WINDOWS_APPS_STUB = /[\\/]Microsoft[\\/]WindowsApps[\\/][^\\/]+$/i
|
|
14
|
+
|
|
13
15
|
const isFile = (file) => {
|
|
14
16
|
try {
|
|
15
|
-
|
|
17
|
+
const st = statSync(file)
|
|
18
|
+
if (!st.isFile()) return false
|
|
19
|
+
// 未安装对应商店应用时 WindowsApps 目录里的执行别名是 0 字节空壳,跳过它免得误认或拉起商店弹窗
|
|
20
|
+
if (WINDOWS_APPS_STUB.test(file) && st.size === 0) return false
|
|
21
|
+
return true
|
|
16
22
|
} catch {
|
|
17
23
|
return false
|
|
18
24
|
}
|
package/lib/config.mjs
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
import { readFile, utimes } from 'node:fs/promises'
|
|
4
4
|
|
|
5
5
|
import { errorKind, keyFormatError, KiokuFailure } from './http.mjs'
|
|
6
|
+
import { serverUrlProblem } from './profile.mjs'
|
|
6
7
|
|
|
7
8
|
const NOT_CONFIGURED =
|
|
8
9
|
'缺少 Kioku 的地址或访问密钥:在 Claude Code 里启用 kioku 插件、填好配置后新开会话,或者设置 KIOKU_SERVER_URL 与 KIOKU_API_KEY'
|
|
@@ -35,15 +36,8 @@ export async function loadConfig(env) {
|
|
|
35
36
|
`无法读取访问密钥文件 ${file}(${fileProblem}):新开会话,或者设置 KIOKU_API_KEY`,
|
|
36
37
|
)
|
|
37
38
|
}
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
protocol = new URL(url).protocol
|
|
41
|
-
} catch {
|
|
42
|
-
throw new KiokuFailure('KIOKU_SERVER_URL 不是有效的地址')
|
|
43
|
-
}
|
|
44
|
-
if (protocol !== 'http:' && protocol !== 'https:') {
|
|
45
|
-
throw new KiokuFailure('KIOKU_SERVER_URL 要以 http:// 或 https:// 开头')
|
|
46
|
-
}
|
|
39
|
+
const urlProblem = serverUrlProblem(url)
|
|
40
|
+
if (urlProblem) throw new KiokuFailure(urlProblem.replace(/^服务地址/, 'KIOKU_SERVER_URL '))
|
|
47
41
|
const problem = keyFormatError(key)
|
|
48
42
|
if (problem) throw new KiokuFailure(problem)
|
|
49
43
|
return { url, key }
|
package/lib/http.mjs
CHANGED
|
@@ -55,3 +55,48 @@ export function isRedirect(status) {
|
|
|
55
55
|
export function failureText(err) {
|
|
56
56
|
return err instanceof KiokuFailure ? err.message : errorKind(err)
|
|
57
57
|
}
|
|
58
|
+
|
|
59
|
+
// 服务端在响应体里给的错误码(与服务端 contracts 的常量一致):
|
|
60
|
+
// database_unavailable 表示数据库尚未配置或暂时无法连接(503)
|
|
61
|
+
export const DATABASE_UNAVAILABLE_CODE = 'database_unavailable'
|
|
62
|
+
|
|
63
|
+
export const INVALID_KEY_TEXT = '访问密钥无效或已吊销'
|
|
64
|
+
export const DATABASE_UNAVAILABLE_TEXT = 'Kioku 的数据库暂时无法连接,请稍后重试'
|
|
65
|
+
|
|
66
|
+
// 服务端明说访问密钥不能用(401):和连不上、响应不对分开
|
|
67
|
+
export class KeyRejected extends KiokuFailure {
|
|
68
|
+
constructor() {
|
|
69
|
+
super(INVALID_KEY_TEXT)
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// 服务端数据库尚未配置或暂时无法连接(503 database_unavailable)
|
|
74
|
+
export class DatabaseUnavailable extends KiokuFailure {
|
|
75
|
+
constructor() {
|
|
76
|
+
super(DATABASE_UNAVAILABLE_TEXT)
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// 响应体里的错误码;没有、或者不像错误码时为 null(服务端写的文字不原样拿来用)
|
|
81
|
+
export function errorCodeOf(data) {
|
|
82
|
+
const code = data?.code
|
|
83
|
+
return typeof code === 'string' && /^[a-z][a-z0-9_]{0,63}$/.test(code) ? code : null
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// 401 与带 database_unavailable 的 503 的统一解读:返回要抛的失败,别的状态返回 null
|
|
87
|
+
export function rejectionOf(status, data) {
|
|
88
|
+
if (status === 401) return new KeyRejected()
|
|
89
|
+
if (status === 503 && errorCodeOf(data) === DATABASE_UNAVAILABLE_CODE) {
|
|
90
|
+
return new DatabaseUnavailable()
|
|
91
|
+
}
|
|
92
|
+
return null
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// 响应文字按 JSON 读,读不懂时为 null
|
|
96
|
+
export function jsonOrNull(text) {
|
|
97
|
+
try {
|
|
98
|
+
return JSON.parse(text)
|
|
99
|
+
} catch {
|
|
100
|
+
return null
|
|
101
|
+
}
|
|
102
|
+
}
|
package/lib/kioku.mjs
CHANGED
|
@@ -5,7 +5,7 @@ import { parseRunArgs, run, USAGE, UsageError } from './run.mjs'
|
|
|
5
5
|
|
|
6
6
|
export { parseRunArgs, run, USAGE, UsageError }
|
|
7
7
|
|
|
8
|
-
const OVERVIEW = `用法:kioku run -e
|
|
8
|
+
const OVERVIEW = `用法:kioku run -e 变量=<标识>[#<字段>] [-e …] [--purpose <用途>] -- <命令> [参数…]
|
|
9
9
|
|
|
10
10
|
插件目录内置的命令行入口仅包含 kioku run(向 Kioku 取凭据,放进环境变量并打码输出)。
|
|
11
11
|
向导、接入管理与记忆读写等完整功能见 @kioku-memory/cli:
|
|
@@ -19,6 +19,7 @@ const OVERVIEW = `用法:kioku run -e 变量=<标识>#<字段> [-e …] [--pur
|
|
|
19
19
|
const FULL_CLI_COMMANDS = new Set([
|
|
20
20
|
'connect',
|
|
21
21
|
'disconnect',
|
|
22
|
+
'migrate',
|
|
22
23
|
'upgrade',
|
|
23
24
|
'status',
|
|
24
25
|
'login',
|
|
@@ -33,6 +34,10 @@ const FULL_CLI_COMMANDS = new Set([
|
|
|
33
34
|
'get',
|
|
34
35
|
'ls',
|
|
35
36
|
'add',
|
|
37
|
+
'edit',
|
|
38
|
+
'delete',
|
|
39
|
+
'rm',
|
|
40
|
+
'boot',
|
|
36
41
|
])
|
|
37
42
|
|
|
38
43
|
export async function main(argv) {
|
package/lib/lifecycle.mjs
CHANGED
|
@@ -4,9 +4,17 @@
|
|
|
4
4
|
// 也不跟着跳转走,访问密钥只发给配置的地址
|
|
5
5
|
|
|
6
6
|
import { execFile, execFileSync } from 'node:child_process'
|
|
7
|
+
import { hostname } from 'node:os'
|
|
7
8
|
import { basename } from 'node:path'
|
|
8
9
|
|
|
9
|
-
import {
|
|
10
|
+
import {
|
|
11
|
+
fetchFailure,
|
|
12
|
+
isRedirect,
|
|
13
|
+
keyFormatError,
|
|
14
|
+
KiokuFailure,
|
|
15
|
+
redirectError,
|
|
16
|
+
rejectionOf,
|
|
17
|
+
} from './http.mjs'
|
|
10
18
|
|
|
11
19
|
// 各事件等待服务端的上限(毫秒),要比平台给钩子的时限短
|
|
12
20
|
export const TIMEOUTS = { 'session.start': 8000, 'prompt.submit': 5000, 'turn.end': 5000 }
|
|
@@ -16,6 +24,29 @@ export const MAX_REPLY = 20_000
|
|
|
16
24
|
export const MAX_SESSION_ID = 200
|
|
17
25
|
const MAX_NAME = 128
|
|
18
26
|
|
|
27
|
+
function stripControl(text) {
|
|
28
|
+
let out = ''
|
|
29
|
+
for (const ch of text) {
|
|
30
|
+
const code = ch.charCodeAt(0)
|
|
31
|
+
if (code >= 0x20 && code !== 0x7f && (code < 0x80 || code > 0x9f)) out += ch
|
|
32
|
+
}
|
|
33
|
+
return out
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function deviceKeyOf(env = process.env) {
|
|
37
|
+
const override = typeof env?.KIOKU_DEVICE_KEY === 'string' ? env.KIOKU_DEVICE_KEY : ''
|
|
38
|
+
let raw = override
|
|
39
|
+
if (!stripControl(raw).trim()) {
|
|
40
|
+
try {
|
|
41
|
+
raw = hostname()
|
|
42
|
+
} catch {
|
|
43
|
+
raw = ''
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
const clean = clip(stripControl(raw).trim(), MAX_NAME).trim()
|
|
47
|
+
return clean || undefined
|
|
48
|
+
}
|
|
49
|
+
|
|
19
50
|
// 配置写错了:访问密钥格式不对(kind 为 key),或者服务地址返回跳转(kind 为 url)。
|
|
20
51
|
// 和没有配置一样,平台可以在会话开始时提示一次;文字不带访问密钥
|
|
21
52
|
export class Misconfigured extends KiokuFailure {
|
|
@@ -47,7 +78,7 @@ export function clip(text, max) {
|
|
|
47
78
|
export function projectOf(cwd) {
|
|
48
79
|
const project = {}
|
|
49
80
|
const dirName = basename(cwd)
|
|
50
|
-
if (dirName) project.dirName = dirName
|
|
81
|
+
if (dirName) project.dirName = clip(dirName, MAX_NAME)
|
|
51
82
|
try {
|
|
52
83
|
const remote = execFileSync('git', ['-C', cwd, 'remote', 'get-url', 'origin'], {
|
|
53
84
|
encoding: 'utf8',
|
|
@@ -55,7 +86,7 @@ export function projectOf(cwd) {
|
|
|
55
86
|
stdio: ['ignore', 'pipe', 'ignore'],
|
|
56
87
|
}).trim()
|
|
57
88
|
const repoName = /([^/:]+?)(?:\.git)?$/.exec(remote)?.[1]
|
|
58
|
-
if (repoName) project.repoName = repoName
|
|
89
|
+
if (repoName) project.repoName = clip(repoName, MAX_NAME)
|
|
59
90
|
} catch {
|
|
60
91
|
// 不是 git 仓库或没有 origin
|
|
61
92
|
}
|
|
@@ -66,7 +97,7 @@ export function projectOf(cwd) {
|
|
|
66
97
|
export function projectOfAsync(cwd) {
|
|
67
98
|
const project = {}
|
|
68
99
|
const dirName = basename(cwd)
|
|
69
|
-
if (dirName) project.dirName = dirName
|
|
100
|
+
if (dirName) project.dirName = clip(dirName, MAX_NAME)
|
|
70
101
|
return new Promise((resolve) => {
|
|
71
102
|
execFile(
|
|
72
103
|
'git',
|
|
@@ -74,7 +105,7 @@ export function projectOfAsync(cwd) {
|
|
|
74
105
|
{ encoding: 'utf8', timeout: 1500 },
|
|
75
106
|
(err, stdout) => {
|
|
76
107
|
const repoName = err ? undefined : /([^/:]+?)(?:\.git)?$/.exec(stdout.trim())?.[1]
|
|
77
|
-
if (repoName) project.repoName = repoName
|
|
108
|
+
if (repoName) project.repoName = clip(repoName, MAX_NAME)
|
|
78
109
|
resolve(project)
|
|
79
110
|
},
|
|
80
111
|
)
|
|
@@ -123,6 +154,10 @@ export async function postEvent(base, key, body, timeout, signal) {
|
|
|
123
154
|
if (isRedirect(res.status)) {
|
|
124
155
|
throw new Misconfigured(redirectError(res.status, res.headers.get('location'), base), 'url')
|
|
125
156
|
}
|
|
157
|
+
if (res.status === 401 || res.status === 503) {
|
|
158
|
+
const rejected = rejectionOf(res.status, await res.json().catch(() => null))
|
|
159
|
+
if (rejected) throw rejected
|
|
160
|
+
}
|
|
126
161
|
if (!res.ok) throw new KiokuFailure(`HTTP ${res.status}`)
|
|
127
162
|
return res
|
|
128
163
|
}
|
package/lib/mcp.mjs
CHANGED
|
@@ -5,21 +5,42 @@ import { randomUUID } from 'node:crypto'
|
|
|
5
5
|
import { readFileSync } from 'node:fs'
|
|
6
6
|
import { chmod, mkdir, rename, rm, writeFile } from 'node:fs/promises'
|
|
7
7
|
|
|
8
|
-
import {
|
|
8
|
+
import {
|
|
9
|
+
fetchFailure,
|
|
10
|
+
isRedirect,
|
|
11
|
+
jsonOrNull,
|
|
12
|
+
KiokuFailure,
|
|
13
|
+
redirectError,
|
|
14
|
+
rejectionOf,
|
|
15
|
+
} from './http.mjs'
|
|
9
16
|
import { profileDir, profileFile } from './profile.mjs'
|
|
10
17
|
import { plain } from './text.mjs'
|
|
11
18
|
|
|
12
19
|
export const TOOLS_TIMEOUT = 8000
|
|
13
20
|
export const TOOL_CALL_TIMEOUT = 30_000
|
|
14
21
|
|
|
15
|
-
//
|
|
22
|
+
// 回答可能是一段事件流:合并同一事件里的多行 data,取最后一条非空载荷
|
|
16
23
|
function payloadOf(text, contentType) {
|
|
17
24
|
if (!contentType.includes('text/event-stream')) return text
|
|
18
|
-
const
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
25
|
+
const events = []
|
|
26
|
+
let current = []
|
|
27
|
+
for (const rawLine of text.split(/\r?\n/)) {
|
|
28
|
+
if (rawLine === '') {
|
|
29
|
+
if (current.length) {
|
|
30
|
+
events.push(current.join('\n'))
|
|
31
|
+
current = []
|
|
32
|
+
}
|
|
33
|
+
continue
|
|
34
|
+
}
|
|
35
|
+
if (rawLine.startsWith('data:')) current.push(rawLine.slice(5).trimStart())
|
|
36
|
+
}
|
|
37
|
+
if (current.length) events.push(current.join('\n'))
|
|
38
|
+
return (
|
|
39
|
+
events
|
|
40
|
+
.map((chunk) => chunk.trim())
|
|
41
|
+
.filter((chunk) => chunk && chunk !== '[DONE]')
|
|
42
|
+
.at(-1) ?? ''
|
|
43
|
+
)
|
|
23
44
|
}
|
|
24
45
|
|
|
25
46
|
// 一次 JSON-RPC 调用,返回 result。连不上、超时、取消、跳转、访问密钥无效、响应不对、服务端报错都以 KiokuFailure 抛出
|
|
@@ -49,7 +70,9 @@ export async function mcpCall({ url, key }, method, params, timeout, signal) {
|
|
|
49
70
|
if (isRedirect(res.status)) {
|
|
50
71
|
throw new KiokuFailure(redirectError(res.status, res.headers.get('location'), url))
|
|
51
72
|
}
|
|
52
|
-
|
|
73
|
+
// 401 与数据库不可用的 503 带着错误码,优先用这边的清晰提示
|
|
74
|
+
const rejected = res.ok ? null : rejectionOf(res.status, jsonOrNull(text))
|
|
75
|
+
if (rejected) throw rejected
|
|
53
76
|
if (!res.ok) throw new KiokuFailure(`Kioku 返回 HTTP ${res.status}`)
|
|
54
77
|
let data
|
|
55
78
|
try {
|
|
@@ -115,19 +138,25 @@ export function readToolCacheSync(platform, env) {
|
|
|
115
138
|
const data = JSON.parse(readFileSync(toolCacheFile(platform, env), 'utf8'))
|
|
116
139
|
if (typeof data?.url !== 'string') return null
|
|
117
140
|
const at = Number.isFinite(data.at) && data.at > 0 ? data.at : 0
|
|
118
|
-
|
|
141
|
+
const keyHash = typeof data.keyHash === 'string' && data.keyHash ? data.keyHash : undefined
|
|
142
|
+
return { url: data.url, ...(keyHash ? { keyHash } : {}), at, tools: toolsOf(data) }
|
|
119
143
|
} catch {
|
|
120
144
|
return null
|
|
121
145
|
}
|
|
122
146
|
}
|
|
123
147
|
|
|
124
148
|
// 写不进去不算失败:下次再取
|
|
125
|
-
export async function writeToolCache(
|
|
149
|
+
export async function writeToolCache(
|
|
150
|
+
platform,
|
|
151
|
+
{ url, keyHash = undefined, tools, at = Date.now() },
|
|
152
|
+
env,
|
|
153
|
+
) {
|
|
126
154
|
const file = toolCacheFile(platform, env)
|
|
127
155
|
const temp = `${file}.${randomUUID()}.tmp`
|
|
128
156
|
try {
|
|
129
157
|
await mkdir(profileDir(env), { recursive: true, mode: 0o700 })
|
|
130
|
-
|
|
158
|
+
const body = { url, ...(keyHash ? { keyHash } : {}), at, tools }
|
|
159
|
+
await writeFile(temp, `${JSON.stringify(body)}\n`, { mode: 0o600, flag: 'wx' })
|
|
131
160
|
await chmod(temp, 0o600)
|
|
132
161
|
await rename(temp, file)
|
|
133
162
|
return true
|
package/lib/profile.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// 没有自己的密钥存储的平台(Codex、pi 这类),地址与访问密钥放在本机的一个文件里:
|
|
2
2
|
// <配置目录>/kioku/<平台>.json,只给本人读写。kioku setup 写它,各平台的钩子与 kioku doctor 读它。
|
|
3
|
-
// 一个平台一个文件:每个平台在 Kioku
|
|
3
|
+
// 一个平台一个文件:每个平台在 Kioku 里使用各自的访问密钥,不共用
|
|
4
4
|
|
|
5
5
|
import { randomUUID } from 'node:crypto'
|
|
6
6
|
import { chmod, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
|
package/lib/run.mjs
CHANGED
|
@@ -10,14 +10,18 @@ import { isatty } from 'node:tty'
|
|
|
10
10
|
import { killTree, launch } from './command.mjs'
|
|
11
11
|
import { loadConfig } from './config.mjs'
|
|
12
12
|
import {
|
|
13
|
+
DatabaseUnavailable,
|
|
13
14
|
errorKind,
|
|
14
15
|
failureText,
|
|
15
16
|
fetchFailure,
|
|
16
17
|
isRedirect,
|
|
18
|
+
KeyRejected,
|
|
17
19
|
KiokuFailure,
|
|
18
20
|
redirectError,
|
|
21
|
+
rejectionOf,
|
|
19
22
|
} from './http.mjs'
|
|
20
23
|
import { createRedactor, MIN_REDACT_CHARS, redactable } from './redact.mjs'
|
|
24
|
+
import { plain } from './text.mjs'
|
|
21
25
|
import { UsageError } from './usage.mjs'
|
|
22
26
|
|
|
23
27
|
// 等 Kioku 取值的上限(毫秒)
|
|
@@ -26,7 +30,8 @@ const TIMEOUT = 15_000
|
|
|
26
30
|
const MAX_REFS = 32
|
|
27
31
|
const MAX_PURPOSE = 200
|
|
28
32
|
const VARIABLE = /^[A-Za-z_][A-Za-z0-9_]*$/
|
|
29
|
-
const
|
|
33
|
+
const SLUG = /^[a-z0-9][a-z0-9._-]{0,63}$/
|
|
34
|
+
const FIELD = /^[a-z0-9][a-z0-9_-]{0,63}$/
|
|
30
35
|
const CONTROL = /\p{Cc}/u
|
|
31
36
|
// 不给命令留这两个变量,免得它把访问密钥或文件的位置顺手打印出来。这不是隔离:
|
|
32
37
|
// 访问密钥文件和命令属于同一个用户,命令照样读得到
|
|
@@ -56,21 +61,21 @@ const NOT_RERAISED = new Set([
|
|
|
56
61
|
'SIGXFSZ',
|
|
57
62
|
])
|
|
58
63
|
|
|
59
|
-
export const USAGE = `用法:kioku run -e
|
|
64
|
+
export const USAGE = `用法:kioku run -e 变量=<标识>[#<字段>] [-e …] [--purpose <用途>] -- <命令> [参数…]
|
|
60
65
|
|
|
61
66
|
向 Kioku 取凭据的值,放进环境变量交给命令;命令行和对话记录里只有变量名。
|
|
62
67
|
命令输出里原样出现的值换成 ***(少于 ${MIN_REDACT_CHARS} 个字符的值除外)。
|
|
63
68
|
打码只防值顺手出现在输出里,不是安全边界。
|
|
64
69
|
|
|
65
|
-
-e
|
|
66
|
-
--purpose <用途>
|
|
67
|
-
-h, --help
|
|
70
|
+
-e 变量=<标识>[#<字段>] 凭据 <标识>(或指定 <字段>)放进这个环境变量,可以写多个
|
|
71
|
+
--purpose <用途> 这次取用的用途,记进访问记录,最多 ${MAX_PURPOSE} 个字;用途里有空格时要加引号
|
|
72
|
+
-h, --help 显示本说明
|
|
68
73
|
|
|
69
74
|
命令不经过 shell 直接执行。参数里写的 $变量 会被外层的 shell 提前展开成空值;
|
|
70
75
|
要在参数里用变量,或者要用管道、重定向时,写成 sh -c '…',整段用单引号,变量放在双引号里:
|
|
71
76
|
|
|
72
|
-
kioku run -e PGPASSWORD=pg-main
|
|
73
|
-
kioku run -e TOKEN=github
|
|
77
|
+
kioku run -e PGPASSWORD=pg-main-password -- psql -h db.example.com -U app
|
|
78
|
+
kioku run -e TOKEN=github-token --purpose '查看 issue' -- sh -c 'curl -H "Authorization: Bearer $TOKEN" https://api.example.com/issues'
|
|
74
79
|
|
|
75
80
|
退出码与命令相同,命令被信号结束时 kioku 也以同一个信号结束;参数不对、取值失败时为 2。
|
|
76
81
|
地址与访问密钥:Claude Code 插件在会话开始时配好;在别处用时设置 KIOKU_SERVER_URL 与 KIOKU_API_KEY。
|
|
@@ -78,7 +83,7 @@ export const USAGE = `用法:kioku run -e 变量=<标识>#<字段> [-e …] [-
|
|
|
78
83
|
|
|
79
84
|
export { UsageError }
|
|
80
85
|
|
|
81
|
-
// 解析 kioku run 的参数。要看说明时返回 { help: true };否则返回 refs
|
|
86
|
+
// 解析 kioku run 的参数。要看说明时返回 { help: true };否则返回 refs(要取的标识与可选字段,同一项只取一次)、
|
|
82
87
|
// variables([变量名, 值在 refs 里的下标])、purpose、command 与 args
|
|
83
88
|
export function parseRunArgs(argv) {
|
|
84
89
|
const refs = []
|
|
@@ -91,13 +96,13 @@ export function parseRunArgs(argv) {
|
|
|
91
96
|
const arg = argv[i]
|
|
92
97
|
if (arg === '-h' || arg === '--help') return { help: true }
|
|
93
98
|
if (arg === '-e') {
|
|
94
|
-
if (++i >= argv.length) throw new UsageError('-e 后面要写
|
|
99
|
+
if (++i >= argv.length) throw new UsageError('-e 后面要写 变量=<标识>[#<字段>]')
|
|
95
100
|
const { name, identifier, field } = parseVariable(argv[i])
|
|
96
101
|
if (variables.has(name)) throw new UsageError(`变量 ${name} 写了两次`)
|
|
97
|
-
const ref = `${identifier}#${field}`
|
|
102
|
+
const ref = `${identifier}#${field ?? ''}`
|
|
98
103
|
if (!refIndex.has(ref)) {
|
|
99
104
|
refIndex.set(ref, refs.length)
|
|
100
|
-
refs.push({ identifier, field })
|
|
105
|
+
refs.push(field === undefined ? { identifier } : { identifier, field })
|
|
101
106
|
}
|
|
102
107
|
variables.set(name, refIndex.get(ref))
|
|
103
108
|
} else if (arg === '--purpose' || arg.startsWith('--purpose=')) {
|
|
@@ -113,22 +118,32 @@ export function parseRunArgs(argv) {
|
|
|
113
118
|
const command = argv[i + 1]
|
|
114
119
|
if (!command) throw new UsageError('-- 后面要写命令')
|
|
115
120
|
if (variables.size === 0) throw new UsageError('至少要写一个 -e')
|
|
116
|
-
if (refs.length > MAX_REFS) throw new UsageError(`一次最多取 ${MAX_REFS}
|
|
121
|
+
if (refs.length > MAX_REFS) throw new UsageError(`一次最多取 ${MAX_REFS} 项`)
|
|
117
122
|
return { refs, variables: [...variables], purpose, command, args: argv.slice(i + 2) }
|
|
118
123
|
}
|
|
119
124
|
|
|
120
125
|
// 等号后面写错时只说格式,不复述写的内容:那里可能误填了值本身
|
|
121
126
|
function parseVariable(spec) {
|
|
122
127
|
const eq = spec.indexOf('=')
|
|
123
|
-
if (eq <= 0) throw new UsageError('-e 要写成
|
|
128
|
+
if (eq <= 0) throw new UsageError('-e 要写成 变量=<标识>[#<字段>]')
|
|
124
129
|
const name = spec.slice(0, eq)
|
|
125
130
|
if (!VARIABLE.test(name)) {
|
|
126
131
|
throw new UsageError(`变量名 ${name} 只能用字母、数字和下划线,不能以数字开头`)
|
|
127
132
|
}
|
|
128
|
-
const
|
|
129
|
-
|
|
133
|
+
const raw = spec.slice(eq + 1)
|
|
134
|
+
const hash = raw.indexOf('#')
|
|
135
|
+
if (hash === -1) {
|
|
136
|
+
if (!SLUG.test(raw)) {
|
|
137
|
+
throw new UsageError(
|
|
138
|
+
`${name} 要写成 ${name}=<标识> 或 ${name}=<标识>#<字段>;标识只用小写字母、数字、.、_ 和 -,以字母或数字开头,最长 64 个字符`,
|
|
139
|
+
)
|
|
140
|
+
}
|
|
141
|
+
return { name, identifier: raw, field: undefined }
|
|
142
|
+
}
|
|
143
|
+
const [identifier, field, ...rest] = raw.split('#')
|
|
144
|
+
if (rest.length > 0 || !SLUG.test(identifier) || !FIELD.test(field ?? '')) {
|
|
130
145
|
throw new UsageError(
|
|
131
|
-
`${name} 要写成 ${name}
|
|
146
|
+
`${name} 要写成 ${name}=<标识> 或 ${name}=<标识>#<字段>;标识只用小写字母、数字、.、_ 和 -,字段名只用小写字母、数字、_ 和 -,以字母或数字开头,最长 64 个字符`,
|
|
132
147
|
)
|
|
133
148
|
}
|
|
134
149
|
return { name, identifier, field }
|
|
@@ -142,14 +157,10 @@ function parsePurpose(value) {
|
|
|
142
157
|
return text || undefined
|
|
143
158
|
}
|
|
144
159
|
|
|
145
|
-
//
|
|
160
|
+
// 服务端的错误文字原样给出,去掉控制与格式字符;万一带着访问密钥也盖掉
|
|
146
161
|
function serverError(data, status, key) {
|
|
147
162
|
const text = typeof data?.error === 'string' ? data.error : ''
|
|
148
|
-
const clean = text
|
|
149
|
-
.split(key)
|
|
150
|
-
.join('***')
|
|
151
|
-
.replace(/\p{Cc}+/gu, ' ')
|
|
152
|
-
.trim()
|
|
163
|
+
const clean = plain(key ? text.split(key).join('***') : text)
|
|
153
164
|
return clean || `Kioku 返回 HTTP ${status}`
|
|
154
165
|
}
|
|
155
166
|
|
|
@@ -157,25 +168,33 @@ function serverError(data, status, key) {
|
|
|
157
168
|
// 格式不对的项跳过,不因为提示让整次失败。打印之前去掉控制字符
|
|
158
169
|
function expiredOf(data) {
|
|
159
170
|
if (!Array.isArray(data?.expired)) return []
|
|
160
|
-
const clean = (text) => text.replace(/\p{Cc}+/gu, ' ').trim()
|
|
161
171
|
return data.expired.flatMap((item) =>
|
|
162
172
|
typeof item?.identifier === 'string' && typeof item.expiresAt === 'string'
|
|
163
|
-
? [{ identifier:
|
|
173
|
+
? [{ identifier: plain(item.identifier), expiresAt: plain(item.expiresAt) }]
|
|
164
174
|
: [],
|
|
165
175
|
)
|
|
166
176
|
}
|
|
167
177
|
|
|
168
|
-
// 按 refs 的顺序取出响应里的值;对不上时为 null
|
|
178
|
+
// 按 refs 的顺序取出响应里的值;对不上时为 null。
|
|
179
|
+
// 请求省略 field 时服务端回 field: 'value';同一个标识同时请求裸标识与 #value 时按响应顺序依次取出
|
|
169
180
|
function valuesOf(data, refs) {
|
|
170
181
|
if (!Array.isArray(data?.values) || data.values.length !== refs.length) return null
|
|
171
|
-
const
|
|
182
|
+
const queues = new Map()
|
|
172
183
|
for (const item of data.values) {
|
|
173
184
|
if (typeof item?.identifier !== 'string' || typeof item.field !== 'string') return null
|
|
174
185
|
if (typeof item.value !== 'string') return null
|
|
175
|
-
|
|
186
|
+
const key = `${item.identifier}#${item.field}`
|
|
187
|
+
const list = queues.get(key)
|
|
188
|
+
if (list) list.push(item.value)
|
|
189
|
+
else queues.set(key, [item.value])
|
|
190
|
+
}
|
|
191
|
+
const values = []
|
|
192
|
+
for (const r of refs) {
|
|
193
|
+
const list = queues.get(`${r.identifier}#${r.field ?? 'value'}`)
|
|
194
|
+
if (!list || list.length === 0) return null
|
|
195
|
+
values.push(list.shift())
|
|
176
196
|
}
|
|
177
|
-
|
|
178
|
-
return values.every((v) => v !== undefined) ? values : null
|
|
197
|
+
return values
|
|
179
198
|
}
|
|
180
199
|
|
|
181
200
|
// 一次请求取全部值:任何一项取不到时整次失败,响应里不带值。连同已到期的凭据一起返回
|
|
@@ -204,6 +223,13 @@ async function resolveValues({ url, key }, refs, purpose) {
|
|
|
204
223
|
} catch {
|
|
205
224
|
// 不是 JSON 时按没有错误文字处理
|
|
206
225
|
}
|
|
226
|
+
// 401 与 503 database_unavailable 优先用这边的清晰提示(服务端原文若误带出当前密钥则留待打码)
|
|
227
|
+
const rejected = res.ok ? null : rejectionOf(res.status, data)
|
|
228
|
+
if (rejected instanceof DatabaseUnavailable) throw rejected
|
|
229
|
+
if (rejected instanceof KeyRejected) {
|
|
230
|
+
const echoed = typeof data?.error === 'string' && data.error.includes(key)
|
|
231
|
+
if (!echoed) throw rejected
|
|
232
|
+
}
|
|
207
233
|
if (!res.ok) throw new KiokuFailure(serverError(data, res.status, key))
|
|
208
234
|
const values = valuesOf(data, refs)
|
|
209
235
|
if (!values) throw new KiokuFailure('Kioku 的响应格式不对')
|
|
@@ -356,11 +382,19 @@ export async function run(argv) {
|
|
|
356
382
|
const withNul = refs.findIndex((_, i) => values[i].includes('\0'))
|
|
357
383
|
if (withNul !== -1) {
|
|
358
384
|
const { identifier, field } = refs[withNul]
|
|
359
|
-
|
|
385
|
+
const label = field === undefined ? identifier : `${identifier}#${field}`
|
|
386
|
+
process.stderr.write(`kioku:${label} 的值含有空字符,放不进环境变量\n`)
|
|
360
387
|
return 2
|
|
361
388
|
}
|
|
362
389
|
const env = { ...process.env }
|
|
363
|
-
|
|
390
|
+
if (process.platform === 'win32') {
|
|
391
|
+
const blocked = new Set(KEY_VARIABLES.map((n) => n.toUpperCase()))
|
|
392
|
+
for (const k of Object.keys(env)) {
|
|
393
|
+
if (blocked.has(k.toUpperCase())) delete env[k]
|
|
394
|
+
}
|
|
395
|
+
} else {
|
|
396
|
+
for (const name of KEY_VARIABLES) delete env[name]
|
|
397
|
+
}
|
|
364
398
|
for (const [name, index] of variables) env[name] = values[index]
|
|
365
399
|
const short = variables.filter(([, index]) => !redactable(values[index])).map(([name]) => name)
|
|
366
400
|
if (short.length > 0) process.stderr.write(`kioku:${short.join('、')} 的值太短,输出里不打码\n`)
|
package/openclaw.plugin.json
CHANGED
|
@@ -8,14 +8,11 @@
|
|
|
8
8
|
"kioku_boot",
|
|
9
9
|
"kioku_search",
|
|
10
10
|
"kioku_get",
|
|
11
|
-
"
|
|
11
|
+
"kioku_browse",
|
|
12
12
|
"kioku_create",
|
|
13
13
|
"kioku_update",
|
|
14
14
|
"kioku_delete",
|
|
15
|
-
"
|
|
16
|
-
"kioku_credential",
|
|
17
|
-
"kioku_credential_save",
|
|
18
|
-
"kioku_credential_delete"
|
|
15
|
+
"kioku_list_credentials"
|
|
19
16
|
]
|
|
20
17
|
},
|
|
21
18
|
"activation": {
|
package/package.json
CHANGED