@kioku-memory/cli 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +7 -0
- package/README.md +151 -2
- package/bin/kioku +36 -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/package.json +29 -4
package/lib/codex.mjs
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
// Codex 这个平台的 kioku setup 与 kioku doctor。
|
|
2
|
+
// Codex 的插件没有自己的配置项,MCP 服务的地址也只能写在用户的 config.toml 里,所以 setup 做三件事:
|
|
3
|
+
// 把服务地址与访问密钥写进本机的文件(钩子读它)、在 config.toml 里加上 Kioku 的 MCP 服务、关掉 Codex 自带的 Memories。
|
|
4
|
+
// config.toml 只按行改:不解析整份 TOML,只认段的标题与要改的那几行。名叫 kioku 的 MCP 服务
|
|
5
|
+
// ([mcp_servers.kioku] 与它的子段)整个归 kioku setup 管。不用标记行圈范围:Codex 自己也会重写这个文件,
|
|
6
|
+
// 注释会被它挪到别的段后面
|
|
7
|
+
|
|
8
|
+
import { readdir, rm } from 'node:fs/promises'
|
|
9
|
+
import { homedir } from 'node:os'
|
|
10
|
+
import { join } from 'node:path'
|
|
11
|
+
|
|
12
|
+
import { readText, safeWrite } from './files.mjs'
|
|
13
|
+
import { KiokuFailure } from './http.mjs'
|
|
14
|
+
import { profileDir, profileFile, readProfile, removeProfile, writeProfile } from './profile.mjs'
|
|
15
|
+
import { resolveTarget } from './target.mjs'
|
|
16
|
+
import { plain as plainText, shownUrl } from './text.mjs'
|
|
17
|
+
|
|
18
|
+
const SERVER = 'mcp_servers.kioku'
|
|
19
|
+
const MARKETPLACE = 'lonelyman0108/kioku-plugins'
|
|
20
|
+
|
|
21
|
+
export function codexHome(env) {
|
|
22
|
+
return env.CODEX_HOME || join(homedir(), '.codex')
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// TOML 的基本字符串:反斜杠与双引号要转义。地址与访问密钥都只有可见的 ASCII 字符
|
|
26
|
+
function quoted(value) {
|
|
27
|
+
return `"${value.replaceAll('\\', '\\\\').replaceAll('"', '\\"')}"`
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function unquoted(value) {
|
|
31
|
+
return (value ?? '').replace(/\\(["\\])/g, '$1')
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// 写进 config.toml 的那几行
|
|
35
|
+
function blockOf({ url, key }) {
|
|
36
|
+
return [
|
|
37
|
+
`[${SERVER}]`,
|
|
38
|
+
`url = ${quoted(`${url}/v1/mcp`)}`,
|
|
39
|
+
'',
|
|
40
|
+
`[${SERVER}.http_headers]`,
|
|
41
|
+
`Authorization = ${quoted(`Bearer ${key}`)}`,
|
|
42
|
+
]
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// 标题里的一段名字:不带引号的,或者带引号的
|
|
46
|
+
const KEY_PART = String.raw`(?:[A-Za-z0-9_-]+|"[^"]*"|'[^']*')`
|
|
47
|
+
const HEADER = new RegExp(
|
|
48
|
+
String.raw`^\s*\[\[?\s*(${KEY_PART}(?:\s*\.\s*${KEY_PART})*)\s*\]\]?\s*(#.*)?$`,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
// 段的标题:[a.b] 或 [[a.b]],返回里面的名字;不是标题时为 null。
|
|
52
|
+
// 名字规整成一种写法再比:点两边的空白去掉,只含普通字符的那一段去掉引号
|
|
53
|
+
function headerOf(line) {
|
|
54
|
+
const name = HEADER.exec(line)?.[1]
|
|
55
|
+
if (name === undefined) return null
|
|
56
|
+
return name
|
|
57
|
+
.replace(/\s*\.\s*/g, '.')
|
|
58
|
+
.replace(/"([A-Za-z0-9_-]+)"|'([A-Za-z0-9_-]+)'/g, (_, a, b) => a ?? b)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// 这一行让没有合上的方括号多了几层:多行的数组里,单独成行的 [1, 2] 不是标题。引号里的不算
|
|
62
|
+
function bracketDelta(line) {
|
|
63
|
+
const bare = line.replace(/"(?:[^"\\]|\\.)*"|'[^']*'/g, '').replace(/#.*$/, '')
|
|
64
|
+
return (bare.match(/\[/g)?.length ?? 0) - (bare.match(/\]/g)?.length ?? 0)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// 把 config.toml 按行读成要用的几样:
|
|
68
|
+
// - owned:kioku 的 MCP 服务占了哪些行
|
|
69
|
+
// - unsupported:这个服务用按行认不出范围的写法定义了(行内表、带点的键),不能再加一段同名的
|
|
70
|
+
// - memories:Memories 的开关写在哪一行;memoriesUnknown:features 用认不出的写法写了
|
|
71
|
+
// - plugin:kioku 插件启用没有
|
|
72
|
+
export function scanConfig(text) {
|
|
73
|
+
const eol = text?.includes('\r\n') ? '\r\n' : '\n'
|
|
74
|
+
const lines = text ? text.split(/\r?\n/) : []
|
|
75
|
+
const found = {
|
|
76
|
+
eol,
|
|
77
|
+
lines,
|
|
78
|
+
owned: [],
|
|
79
|
+
unsupported: false,
|
|
80
|
+
memories: null,
|
|
81
|
+
memoriesUnknown: false,
|
|
82
|
+
plugin: false,
|
|
83
|
+
}
|
|
84
|
+
let section = ''
|
|
85
|
+
let depth = 0
|
|
86
|
+
lines.forEach((line, index) => {
|
|
87
|
+
const header = depth === 0 ? headerOf(line) : null
|
|
88
|
+
if (header !== null) section = header
|
|
89
|
+
else depth = Math.max(0, depth + bracketDelta(line))
|
|
90
|
+
if (section === SERVER || section.startsWith(`${SERVER}.`)) {
|
|
91
|
+
found.owned.push(index)
|
|
92
|
+
return
|
|
93
|
+
}
|
|
94
|
+
if (header !== null) return
|
|
95
|
+
// 这个服务的别的写法:最前面的 mcp_servers.kioku…、mcp_servers = { kioku… },或者 [mcp_servers] 段里的 kioku
|
|
96
|
+
const quotedName = String.raw`["']?kioku["']?`
|
|
97
|
+
if (
|
|
98
|
+
(section === '' &&
|
|
99
|
+
new RegExp(String.raw`^\s*mcp_servers\s*(\.\s*${quotedName}\s*[.=]|=.*\bkioku\b)`).test(
|
|
100
|
+
line,
|
|
101
|
+
)) ||
|
|
102
|
+
(section === 'mcp_servers' && new RegExp(String.raw`^\s*${quotedName}\s*[.=]`).test(line))
|
|
103
|
+
) {
|
|
104
|
+
found.unsupported = true
|
|
105
|
+
}
|
|
106
|
+
// Memories 的开关:[features] 段里的 memories,或者写在最前面的 features.memories
|
|
107
|
+
const name = String.raw`["']?memories["']?`
|
|
108
|
+
const key =
|
|
109
|
+
section === 'features' ? name : section === '' ? String.raw`features\s*\.\s*${name}` : null
|
|
110
|
+
const flag = key && new RegExp(String.raw`^(\s*${key}\s*=\s*)(true|false)\b(.*)$`).exec(line)
|
|
111
|
+
if (flag) found.memories = { index, value: flag[2] === 'true', parts: flag }
|
|
112
|
+
// features 写成行内表时认不出里面的开关
|
|
113
|
+
if (section === '' && /^\s*features\s*=/.test(line)) found.memoriesUnknown = true
|
|
114
|
+
// 插件:[plugins."kioku@<市场>"] 段里的 enabled = true
|
|
115
|
+
if (/^plugins\.["']kioku@[^"']+["']$/.test(section) && /^\s*enabled\s*=\s*true\b/.test(line)) {
|
|
116
|
+
found.plugin = true
|
|
117
|
+
}
|
|
118
|
+
})
|
|
119
|
+
// 这一段后面的空行与注释不算它的(注释多半是写给下一段的):去掉这一段时不连带去掉
|
|
120
|
+
while (found.owned.length && /^\s*(#.*)?$/.test(lines[found.owned.at(-1)])) found.owned.pop()
|
|
121
|
+
return found
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// kioku 的 MCP 服务现在写的地址与访问密钥;没有这个服务时为 null,有但认不出写法的那一项为空
|
|
125
|
+
export function blockValues(found) {
|
|
126
|
+
if (!found.owned.length) return null
|
|
127
|
+
const inside = found.owned.map((index) => found.lines[index]).join('\n')
|
|
128
|
+
const url = /^\s*url\s*=\s*"((?:[^"\\]|\\.)*)"/m.exec(inside)?.[1]
|
|
129
|
+
const key = /\bAuthorization\s*=\s*"Bearer ((?:[^"\\]|\\.)*)"/.exec(inside)?.[1]
|
|
130
|
+
// rawUrl 是原样写着的地址,只用来显示
|
|
131
|
+
return { url: unquoted(url).replace(/\/v1\/mcp$/, ''), key: unquoted(key), rawUrl: unquoted(url) }
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// 新的全文:去掉 kioku 的 MCP 服务原来的那些行,把 block 加在最后(为 null 时只去掉;keep 为真时这一段原样留在原处),
|
|
135
|
+
// memoriesOff 为真时把 Memories 关掉。别的行原样不动,只收拾去掉的地方两边多出来的空行
|
|
136
|
+
function rewrite(found, block, { memoriesOff, keep = false }) {
|
|
137
|
+
const owned = new Set(keep ? [] : found.owned)
|
|
138
|
+
const lines = []
|
|
139
|
+
found.lines.forEach((line, index) => {
|
|
140
|
+
if (owned.has(index)) return
|
|
141
|
+
// 去掉一段之后,它前后的空行并成一行
|
|
142
|
+
if (line === '' && owned.has(index - 1) && (lines.at(-1) ?? '') === '') return
|
|
143
|
+
if (memoriesOff && found.memories?.value && index === found.memories.index) {
|
|
144
|
+
const [, head, , tail] = found.memories.parts
|
|
145
|
+
lines.push(`${head}false${tail}`)
|
|
146
|
+
} else lines.push(line)
|
|
147
|
+
})
|
|
148
|
+
if (!owned.size && !block) return lines.join(found.eol)
|
|
149
|
+
// 文件以一个换行结尾,新的一段前面空一行
|
|
150
|
+
while (lines.length && lines.at(-1) === '') lines.pop()
|
|
151
|
+
if (block) lines.push(...(lines.length ? [''] : []), ...block)
|
|
152
|
+
return lines.length ? `${lines.join(found.eol)}${found.eol}` : ''
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// 现在的 config.toml 里有没有写着访问密钥:有的话不留备份,免得撤销、换访问密钥之后旧的还留在备份里
|
|
156
|
+
function holdsKey(found) {
|
|
157
|
+
return Boolean(blockValues(found)?.key)
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// 记下的用户输入(钩子在每轮提交时写的):撤销时一起删掉
|
|
161
|
+
async function removePendingTurns(env) {
|
|
162
|
+
const dirs = [join(profileDir(env), 'codex-state')]
|
|
163
|
+
const data = join(codexHome(env), 'plugins', 'data')
|
|
164
|
+
for (const name of await readdir(data).catch(() => [])) {
|
|
165
|
+
if (name.startsWith('kioku-')) dirs.push(join(data, name, 'turns'))
|
|
166
|
+
}
|
|
167
|
+
for (const dir of dirs) await rm(dir, { recursive: true, force: true }).catch(() => {})
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// 地址只打印协议、主机与路径;解析不了的压成一行再打印
|
|
171
|
+
function shown(url) {
|
|
172
|
+
try {
|
|
173
|
+
return shownUrl(url)
|
|
174
|
+
} catch {
|
|
175
|
+
return plainText(url)
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const NEXT_STEPS = `接下来在 Codex 这一边:
|
|
180
|
+
1. codex plugin marketplace add ${MARKETPLACE}
|
|
181
|
+
2. codex plugin add kioku@kioku
|
|
182
|
+
3. 打开 codex,在 /hooks 里信任 kioku 的三个钩子(没信任过的钩子不会运行)
|
|
183
|
+
`
|
|
184
|
+
|
|
185
|
+
async function undo({ dryRun }, { env, out }) {
|
|
186
|
+
const file = join(codexHome(env), 'config.toml')
|
|
187
|
+
const text = await readText(file)
|
|
188
|
+
const found = scanConfig(text)
|
|
189
|
+
const profile = profileFile('codex', env)
|
|
190
|
+
if (!found.owned.length) out.write(`${file} 里没有 Kioku 的 MCP 服务,不用改\n`)
|
|
191
|
+
else {
|
|
192
|
+
out.write(`${file}\n ${SERVER}:去掉\n`)
|
|
193
|
+
if (!dryRun) {
|
|
194
|
+
// 现在的文件里写着访问密钥,不留备份
|
|
195
|
+
await safeWrite(file, rewrite(found, null, { memoriesOff: false }), text, { backup: false })
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
if (found.unsupported) {
|
|
199
|
+
out.write(`${file} 里还有用别的写法定义的 kioku 服务,没有改动它,要手动去掉\n`)
|
|
200
|
+
}
|
|
201
|
+
if (dryRun) out.write(`${profile}:删掉\n没有写入(--dry-run)\n`)
|
|
202
|
+
else {
|
|
203
|
+
if (await removeProfile('codex', env)) out.write(`已删掉 ${profile}\n`)
|
|
204
|
+
await removePendingTurns(env)
|
|
205
|
+
}
|
|
206
|
+
out.write('Codex 自带的 Memories 没有重新打开:要用的话运行 codex features enable memories\n')
|
|
207
|
+
out.write('插件要另外卸载:codex plugin remove kioku@kioku\n')
|
|
208
|
+
return 0
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export async function setupCodex(options, io) {
|
|
212
|
+
const { env, out } = io
|
|
213
|
+
if (options.undo) return undo(options, io)
|
|
214
|
+
const file = join(codexHome(env), 'config.toml')
|
|
215
|
+
const text = await readText(file)
|
|
216
|
+
const found = scanConfig(text)
|
|
217
|
+
|
|
218
|
+
const refuseUnsupported = () => {
|
|
219
|
+
if (!found.unsupported) return
|
|
220
|
+
throw new KiokuFailure(
|
|
221
|
+
`${file} 里已经用行内表或带点的键定义了 kioku 这个 MCP 服务,没有改动它:删掉那个定义后重新运行`,
|
|
222
|
+
)
|
|
223
|
+
}
|
|
224
|
+
// 要走浏览器授权时先看这个:访问密钥签发了却写不进去的话,会留下一个没人拿着的
|
|
225
|
+
const { url, key, saved } = await resolveTarget({ id: 'codex', name: 'Codex' }, options, {
|
|
226
|
+
...io,
|
|
227
|
+
beforeLogin: refuseUnsupported,
|
|
228
|
+
})
|
|
229
|
+
// 地址与访问密钥都定下来之后、写文件之前再看一次
|
|
230
|
+
refuseUnsupported()
|
|
231
|
+
|
|
232
|
+
const before = blockValues(found)
|
|
233
|
+
const sameBlock = Boolean(before && key && before.url === url && before.key === key)
|
|
234
|
+
const changes = []
|
|
235
|
+
if (!sameBlock) {
|
|
236
|
+
const was = !before ? '(未设置)' : before.rawUrl ? shown(before.rawUrl) : '(认不出的写法)'
|
|
237
|
+
// 地址没变时只是换访问密钥,不把同一个地址写两遍
|
|
238
|
+
if (before?.url === url) changes.push(` ${SERVER}:换访问密钥`)
|
|
239
|
+
else changes.push(` ${SERVER}:${was} → ${shown(url)}/v1/mcp`)
|
|
240
|
+
}
|
|
241
|
+
if (found.memories?.value) changes.push(' features.memories:true → false')
|
|
242
|
+
const profile = profileFile('codex', env)
|
|
243
|
+
const sameProfile = Boolean(saved && saved.url === url && saved.key === key)
|
|
244
|
+
|
|
245
|
+
if (!changes.length) out.write(`${file} 不用改\n`)
|
|
246
|
+
else out.write(`${file}\n${changes.join('\n')}\n`)
|
|
247
|
+
if (!sameProfile) out.write(`${profile}:写入服务地址与访问密钥(只给本人读写)\n`)
|
|
248
|
+
if (options.dryRun) {
|
|
249
|
+
out.write('没有写入(--dry-run)\n')
|
|
250
|
+
return 0
|
|
251
|
+
}
|
|
252
|
+
if (changes.length) {
|
|
253
|
+
const body = sameBlock
|
|
254
|
+
? rewrite(found, null, { memoriesOff: true, keep: true })
|
|
255
|
+
: rewrite(found, blockOf({ url, key }), { memoriesOff: true })
|
|
256
|
+
const backedUp = await safeWrite(file, body, text, { backup: !holdsKey(found) })
|
|
257
|
+
if (backedUp) out.write(`原来的设置备份在 ${file}.kioku-backup\n`)
|
|
258
|
+
}
|
|
259
|
+
if (!sameProfile) await writeProfile('codex', { url, key }, env)
|
|
260
|
+
if (found.memoriesUnknown) {
|
|
261
|
+
out.write(
|
|
262
|
+
`! ${file} 里 features 的写法认不出来,没有核对 Memories:运行 codex features disable memories 关掉它\n`,
|
|
263
|
+
)
|
|
264
|
+
}
|
|
265
|
+
out.write(`Codex 已配好,新开会话生效。\n${found.plugin ? '' : NEXT_STEPS}`)
|
|
266
|
+
return 0
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// kioku login 申请之前先看:config.toml 写不写得进去
|
|
270
|
+
export async function preflightCodex({ env }) {
|
|
271
|
+
const file = join(codexHome(env), 'config.toml')
|
|
272
|
+
if (scanConfig(await readText(file)).unsupported) {
|
|
273
|
+
throw new KiokuFailure(
|
|
274
|
+
`${file} 里已经用行内表或带点的键定义了 kioku 这个 MCP 服务:删掉那个定义后重新运行`,
|
|
275
|
+
)
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
export async function inspectCodex({ env }, { ok, warn, bad, note }) {
|
|
280
|
+
const file = join(codexHome(env), 'config.toml')
|
|
281
|
+
const found = scanConfig(await readText(file))
|
|
282
|
+
const profile = await readProfile('codex', env).catch(() => null)
|
|
283
|
+
if (!profile) {
|
|
284
|
+
warn('没有 kioku setup codex 写下的地址与访问密钥,钩子不会生效:运行 kioku setup codex')
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
const block = blockValues(found)
|
|
288
|
+
if (found.unsupported) {
|
|
289
|
+
warn(`${file} 里的 kioku 服务用了行内表或带点的键,没有核对它:改成 kioku setup codex 的写法`)
|
|
290
|
+
} else if (!block) {
|
|
291
|
+
warn(`${file} 里没有 Kioku 的 MCP 服务,读写记忆的工具用不了:运行 kioku setup codex`)
|
|
292
|
+
} else if (profile && (block.url !== profile.url || block.key !== profile.key)) {
|
|
293
|
+
bad(`${file} 里 Kioku 的 MCP 服务和钩子用的地址或访问密钥对不上:重新运行 kioku setup codex`)
|
|
294
|
+
} else ok('Codex 里配了 Kioku 的 MCP 服务')
|
|
295
|
+
|
|
296
|
+
if (found.plugin) ok('Codex 的 kioku 插件已启用')
|
|
297
|
+
else {
|
|
298
|
+
warn(
|
|
299
|
+
`Codex 的 kioku 插件没有启用:codex plugin marketplace add ${MARKETPLACE},再 codex plugin add kioku@kioku`,
|
|
300
|
+
)
|
|
301
|
+
}
|
|
302
|
+
note('钩子要在 Codex 的 /hooks 里信任过才会运行,这里查不到')
|
|
303
|
+
|
|
304
|
+
if (found.memoriesUnknown && !found.memories) {
|
|
305
|
+
warn(`${file} 里 features 的写法认不出来,没有核对 Memories:用 codex features list 看它开没开`)
|
|
306
|
+
} else if (found.memories?.value) {
|
|
307
|
+
warn('Codex 自带的 Memories 开着,会和 Kioku 各记一份:运行 kioku setup codex 关掉它')
|
|
308
|
+
} else ok('Codex 自带的 Memories 没有启用')
|
|
309
|
+
}
|
package/lib/command.mjs
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
// 起 npm 装的那类外部命令(openclaw、hermes,以及 kioku run 要跑的命令)。
|
|
2
|
+
// Windows 上这类命令是 .cmd 文件,不经 cmd.exe 起不来(直接起会报找不到,或者被 Node 拒绝),
|
|
3
|
+
// 而经 cmd.exe 时参数要按它的规则转义,否则参数里的 & | % 这类字符会被当成命令。
|
|
4
|
+
// 别的系统上什么都不做,原样交给系统:找命令、判断能不能执行都是系统的事。
|
|
5
|
+
// 转义的规则照 cross-spawn 的做法写(MIT,来源登记在 NOTICE)
|
|
6
|
+
|
|
7
|
+
import { execFile, spawn } from 'node:child_process'
|
|
8
|
+
import { statSync } from 'node:fs'
|
|
9
|
+
import { win32 } from 'node:path'
|
|
10
|
+
|
|
11
|
+
import { KiokuFailure } from './http.mjs'
|
|
12
|
+
|
|
13
|
+
const isFile = (file) => {
|
|
14
|
+
try {
|
|
15
|
+
return statSync(file).isFile()
|
|
16
|
+
} catch {
|
|
17
|
+
return false
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// Windows 的环境变量名不分大小写。同一个名字写了几种大小写时(Path 与 PATH),
|
|
22
|
+
// 取排序后的第一个:Node 把环境交给子进程时也是这样取的,两边看到的要是同一个
|
|
23
|
+
export function envValue(env, name) {
|
|
24
|
+
const key = Object.keys(env)
|
|
25
|
+
.filter((item) => item.toLowerCase() === name.toLowerCase())
|
|
26
|
+
.sort()[0]
|
|
27
|
+
return key === undefined ? undefined : env[key]
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Windows 上一个命令的完整路径;找不到为 null。名字里带目录时只看这个位置,否则在 PATH 里逐个目录找。
|
|
31
|
+
// 名字没写扩展名时只按 PATHEXT 补上扩展名找,不找原样的名字:npm 在 .cmd 旁边还放着一个同名、
|
|
32
|
+
// 没有扩展名的脚本(给 sh 用的),Windows 起不了它
|
|
33
|
+
export function findCommand(name, env, { exists = isFile } = {}) {
|
|
34
|
+
if (typeof name !== 'string' || !name) return null
|
|
35
|
+
const extensions = (envValue(env, 'PATHEXT') || '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean)
|
|
36
|
+
const suffixes = win32.extname(name) ? ['', ...extensions] : extensions
|
|
37
|
+
const dirs = /[\\/]/.test(name)
|
|
38
|
+
? ['']
|
|
39
|
+
: (envValue(env, 'PATH') ?? '')
|
|
40
|
+
.split(win32.delimiter)
|
|
41
|
+
// 带空格的目录有人会加上引号
|
|
42
|
+
.map((dir) => dir.replace(/^"(.*)"$/, '$1'))
|
|
43
|
+
.filter(Boolean)
|
|
44
|
+
for (const dir of dirs) {
|
|
45
|
+
for (const suffix of suffixes) {
|
|
46
|
+
const file = (dir ? win32.join(dir, name) : name) + suffix
|
|
47
|
+
if (exists(file)) return file
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return null
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// cmd.exe 认作有特殊含义的字符
|
|
54
|
+
const META = /([()\][%!^"`<>&|;, *?])/g
|
|
55
|
+
|
|
56
|
+
// 一个参数在 cmd.exe 的命令行里的写法:先按 Windows 程序解析参数的规则加引号、处理反斜杠与引号,
|
|
57
|
+
// 再给 cmd.exe 自己的特殊字符加 ^。经 node_modules/.bin 里的 .cmd 转一道的要转义两遍(它里面又解析一次)
|
|
58
|
+
function escapeArgument(value, twice) {
|
|
59
|
+
let arg = String(value)
|
|
60
|
+
arg = arg.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"')
|
|
61
|
+
arg = arg.replace(/(?=(\\+?)?)\1$/, '$1$1')
|
|
62
|
+
arg = `"${arg}"`.replace(META, '^$1')
|
|
63
|
+
return twice ? arg.replace(META, '^$1') : arg
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// 怎么起这个命令:{ file, args, options, shell },交给 spawn、execFile;Windows 上找不到这个命令时为 null。
|
|
67
|
+
// shell 为真表示中间隔着一层 cmd.exe,结束它要用 killTree。别的系统上原样返回,找不到由系统报 ENOENT
|
|
68
|
+
export function launch(name, args, env, { platform = process.platform, exists } = {}) {
|
|
69
|
+
if (platform !== 'win32') return { file: name, args, options: {}, shell: false }
|
|
70
|
+
const file = findCommand(name, env, { exists })
|
|
71
|
+
if (!file) return null
|
|
72
|
+
if (!/\.(cmd|bat)$/i.test(file)) return { file, args, options: {}, shell: false }
|
|
73
|
+
// cmd.exe 把换行当成一行命令的结尾,后面的参数会悄悄丢掉:不起
|
|
74
|
+
if ([file, ...args].some((item) => /[\r\n]/.test(String(item)))) {
|
|
75
|
+
throw new KiokuFailure('参数里有换行,经 cmd.exe 起的命令收不到完整的参数')
|
|
76
|
+
}
|
|
77
|
+
const twice = /node_modules[\\/]\.bin[\\/][^\\/]+\.cmd$/i.test(file)
|
|
78
|
+
const line = [file.replace(META, '^$1'), ...args.map((arg) => escapeArgument(arg, twice))]
|
|
79
|
+
return {
|
|
80
|
+
file: envValue(env, 'ComSpec') || 'cmd.exe',
|
|
81
|
+
// /d 不跑注册表里的自动命令,/s 加外层引号让整行原样交给 /c
|
|
82
|
+
args: ['/d', '/s', '/c', `"${line.join(' ')}"`],
|
|
83
|
+
// 这一行已经按 cmd.exe 的规则写好了,不让 Node 再加一层引号
|
|
84
|
+
options: { windowsVerbatimArguments: true },
|
|
85
|
+
shell: true,
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// 结束一个起好的命令。隔着 cmd.exe 时只结束它的话,真正的命令还活着、还占着输出的管道,
|
|
90
|
+
// 所以连它下面的进程一起结束(Windows 上没有信号可转,只能强行结束)
|
|
91
|
+
export function killTree(child, signal, { shell, platform = process.platform } = {}) {
|
|
92
|
+
if (platform !== 'win32' || !shell || child.pid === undefined) return child.kill(signal)
|
|
93
|
+
try {
|
|
94
|
+
spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' }).on(
|
|
95
|
+
'error',
|
|
96
|
+
() => child.kill(),
|
|
97
|
+
)
|
|
98
|
+
return true
|
|
99
|
+
} catch {
|
|
100
|
+
return child.kill()
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// 跑一个命令到结束,收下它的输出:{ found: false }(没有这个命令),
|
|
105
|
+
// 或者 { found: true, ok, stdout, output }(output 是两路输出合在一起,只用来认是哪种失败)。
|
|
106
|
+
// 超过时限就结束它(连同它下面的进程),算失败。不抛错
|
|
107
|
+
export function capture(name, args, env, { timeout, maxBuffer = 8 * 1024 * 1024 } = {}) {
|
|
108
|
+
let run
|
|
109
|
+
try {
|
|
110
|
+
run = launch(name, args, env)
|
|
111
|
+
} catch {
|
|
112
|
+
return Promise.resolve({ found: true, ok: false, stdout: '', output: '' })
|
|
113
|
+
}
|
|
114
|
+
if (!run) return Promise.resolve({ found: false })
|
|
115
|
+
return new Promise((resolve) => {
|
|
116
|
+
let timer
|
|
117
|
+
const child = execFile(
|
|
118
|
+
run.file,
|
|
119
|
+
run.args,
|
|
120
|
+
{ env, maxBuffer, ...run.options },
|
|
121
|
+
(err, stdout, stderr) => {
|
|
122
|
+
clearTimeout(timer)
|
|
123
|
+
if (err?.code === 'ENOENT') resolve({ found: false })
|
|
124
|
+
else {
|
|
125
|
+
const out = String(stdout ?? '')
|
|
126
|
+
resolve({ found: true, ok: !err, stdout: out, output: `${out}\n${stderr ?? ''}` })
|
|
127
|
+
}
|
|
128
|
+
},
|
|
129
|
+
)
|
|
130
|
+
if (timeout) {
|
|
131
|
+
timer = setTimeout(() => killTree(child, 'SIGTERM', { shell: run.shell }), timeout)
|
|
132
|
+
timer.unref?.()
|
|
133
|
+
}
|
|
134
|
+
})
|
|
135
|
+
}
|
package/lib/config.mjs
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// kioku 命令的地址与访问密钥:从环境变量与访问密钥文件读
|
|
2
|
+
|
|
3
|
+
import { readFile, utimes } from 'node:fs/promises'
|
|
4
|
+
|
|
5
|
+
import { errorKind, keyFormatError, KiokuFailure } from './http.mjs'
|
|
6
|
+
|
|
7
|
+
const NOT_CONFIGURED =
|
|
8
|
+
'缺少 Kioku 的地址或访问密钥:在 Claude Code 里启用 kioku 插件、填好配置后新开会话,或者设置 KIOKU_SERVER_URL 与 KIOKU_API_KEY'
|
|
9
|
+
|
|
10
|
+
// 地址或访问密钥根本没有配(区别于配了但不对)
|
|
11
|
+
export class NotConfigured extends KiokuFailure {}
|
|
12
|
+
|
|
13
|
+
// 地址与访问密钥。访问密钥先读插件在会话开始时配好的 KIOKU_API_KEY_FILE,读不到再用 KIOKU_API_KEY;
|
|
14
|
+
// 两样都没有才报错,报错只写文件的位置与错误类别
|
|
15
|
+
export async function loadConfig(env) {
|
|
16
|
+
const url = (env.KIOKU_SERVER_URL ?? '').trim().replace(/\/+$/, '')
|
|
17
|
+
const file = env.KIOKU_API_KEY_FILE
|
|
18
|
+
let key = ''
|
|
19
|
+
let fileProblem
|
|
20
|
+
if (file) {
|
|
21
|
+
try {
|
|
22
|
+
key = (await readFile(file, 'utf8')).trim()
|
|
23
|
+
if (!key) fileProblem = '文件是空的'
|
|
24
|
+
} catch (err) {
|
|
25
|
+
fileProblem = errorKind(err)
|
|
26
|
+
}
|
|
27
|
+
// 用的时候更新修改时间:会话开始时会删掉很久没用过的访问密钥文件
|
|
28
|
+
if (key) await utimes(file, new Date(), new Date()).catch(() => {})
|
|
29
|
+
}
|
|
30
|
+
if (!key) key = (env.KIOKU_API_KEY ?? '').trim()
|
|
31
|
+
if (!url) throw new NotConfigured(NOT_CONFIGURED)
|
|
32
|
+
if (!key) {
|
|
33
|
+
if (!fileProblem) throw new NotConfigured(NOT_CONFIGURED)
|
|
34
|
+
throw new KiokuFailure(
|
|
35
|
+
`无法读取访问密钥文件 ${file}(${fileProblem}):新开会话,或者设置 KIOKU_API_KEY`,
|
|
36
|
+
)
|
|
37
|
+
}
|
|
38
|
+
let protocol
|
|
39
|
+
try {
|
|
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
|
+
}
|
|
47
|
+
const problem = keyFormatError(key)
|
|
48
|
+
if (problem) throw new KiokuFailure(problem)
|
|
49
|
+
return { url, key }
|
|
50
|
+
}
|
package/lib/doctor.mjs
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
// kioku doctor:检查地址与访问密钥能不能用、访问密钥的权限,以及平台这一边配好没有。
|
|
2
|
+
// 每项一行:✓ 正常,! 要留意,✗ 有问题;有 ✗ 时退出码为 1
|
|
3
|
+
|
|
4
|
+
import { loadConfig, NotConfigured } from './config.mjs'
|
|
5
|
+
import { whoami } from './api.mjs'
|
|
6
|
+
import { failureText, KiokuFailure } from './http.mjs'
|
|
7
|
+
import { detectPlatform, platformNames, PLATFORMS } from './platforms.mjs'
|
|
8
|
+
import { readSettings } from './files.mjs'
|
|
9
|
+
import { plain, shownUrl } from './text.mjs'
|
|
10
|
+
import { UsageError } from './usage.mjs'
|
|
11
|
+
|
|
12
|
+
export const DOCTOR_USAGE = `用法:kioku doctor [平台]
|
|
13
|
+
|
|
14
|
+
检查 Kioku 的地址与访问密钥、访问密钥的权限,以及平台的配置(插件是否启用、自带的长期记忆是否已停用)。
|
|
15
|
+
|
|
16
|
+
[平台] ${platformNames()};不写时按当前所在的会话认,认不出就只查地址与访问密钥
|
|
17
|
+
|
|
18
|
+
有问题的项以 ✗ 开头,这时退出码为 1。
|
|
19
|
+
`
|
|
20
|
+
|
|
21
|
+
// 与管理界面的用词一致
|
|
22
|
+
const LAYERS = {
|
|
23
|
+
core: '通用',
|
|
24
|
+
persona: '人格',
|
|
25
|
+
app: '应用',
|
|
26
|
+
user: '本人',
|
|
27
|
+
subject: '联系人',
|
|
28
|
+
episode: '会话',
|
|
29
|
+
}
|
|
30
|
+
const SENSITIVITIES = { public: '公开', internal: '内部', private: '私密', secret: '机密' }
|
|
31
|
+
const CAPABILITIES = { none: '不可用', use: '取用', manage: '管理' }
|
|
32
|
+
|
|
33
|
+
function named(names, value) {
|
|
34
|
+
return Object.hasOwn(names, value) ? names[value] : plain(value)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function layersText(layers) {
|
|
38
|
+
if (!Array.isArray(layers) || !layers.length) return '无'
|
|
39
|
+
return layers.map((layer) => named(LAYERS, layer)).join('、')
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function parseDoctorArgs(argv) {
|
|
43
|
+
const names = []
|
|
44
|
+
for (const arg of argv) {
|
|
45
|
+
if (arg.startsWith('-')) throw new UsageError(`不认识的选项 ${arg}`)
|
|
46
|
+
names.push(arg)
|
|
47
|
+
}
|
|
48
|
+
if (names.length > 1) throw new UsageError('最多写一个平台')
|
|
49
|
+
if (names.length && !Object.hasOwn(PLATFORMS, names[0])) {
|
|
50
|
+
throw new UsageError(`不认识的平台 ${names[0]},可以用的:${platformNames()}`)
|
|
51
|
+
}
|
|
52
|
+
return { platform: names[0] ?? null }
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export async function doctor(
|
|
56
|
+
argv,
|
|
57
|
+
{ env = process.env, out = process.stdout, cwd = process.cwd() } = {},
|
|
58
|
+
) {
|
|
59
|
+
const id = parseDoctorArgs(argv).platform ?? detectPlatform(env)
|
|
60
|
+
const platform = id ? PLATFORMS[id] : null
|
|
61
|
+
let failed = false
|
|
62
|
+
const ok = (text) => out.write(`✓ ${text}\n`)
|
|
63
|
+
const warn = (text) => out.write(`! ${text}\n`)
|
|
64
|
+
const bad = (text) => {
|
|
65
|
+
failed = true
|
|
66
|
+
out.write(`✗ ${text}\n`)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
let who = null
|
|
70
|
+
try {
|
|
71
|
+
// 平台把地址与访问密钥放在自己的文件里时先读它,没有再看环境变量
|
|
72
|
+
const profile = platform?.readConfig ? await platform.readConfig(env) : null
|
|
73
|
+
let config = profile
|
|
74
|
+
if (!config) {
|
|
75
|
+
try {
|
|
76
|
+
config = await loadConfig(env)
|
|
77
|
+
} catch (err) {
|
|
78
|
+
// 这个平台有自己放配置的地方、却什么都没配:说怎么配,不说别的平台的做法。
|
|
79
|
+
// 环境变量里配了但不对的(地址无效、访问密钥文件读不了)照原样报
|
|
80
|
+
if (platform?.readConfig && err instanceof NotConfigured) {
|
|
81
|
+
throw new KiokuFailure(`还没有给 ${platform.name} 配过:运行 kioku setup ${id}`)
|
|
82
|
+
}
|
|
83
|
+
throw err
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
ok(`地址 ${shownUrl(config.url)}${profile ? `(${profile.file})` : ''}`)
|
|
87
|
+
who = await whoami(config)
|
|
88
|
+
} catch (err) {
|
|
89
|
+
bad(failureText(err))
|
|
90
|
+
}
|
|
91
|
+
if (who) {
|
|
92
|
+
const { app, scopes } = who
|
|
93
|
+
ok(
|
|
94
|
+
`访问密钥可用:应用 ${plain(app.name)}(${plain(app.slug)}),运行时 ${plain(app.runtimeFamily)}`,
|
|
95
|
+
)
|
|
96
|
+
out.write(` 读:${layersText(scopes.readLayers)}\n`)
|
|
97
|
+
out.write(` 写:${layersText(scopes.writeLayers)}\n`)
|
|
98
|
+
out.write(` 最高敏感级:${named(SENSITIVITIES, scopes.maxSensitivity)}\n`)
|
|
99
|
+
out.write(` 凭据:${named(CAPABILITIES, scopes.credentials ?? 'none')}\n`)
|
|
100
|
+
if (platform && app.runtimeFamily !== platform.runtimeFamily) {
|
|
101
|
+
warn(
|
|
102
|
+
`这个应用的运行时不是 ${platform.runtimeFamily},注入的内容不按 ${platform.name} 的格式:在管理界面为 ${platform.name} 另建一个应用`,
|
|
103
|
+
)
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
if (!platform) {
|
|
108
|
+
out.write(`没有认出平台,只查了地址与访问密钥;要查平台的配置,写上平台:${platformNames()}\n`)
|
|
109
|
+
return failed ? 1 : 0
|
|
110
|
+
}
|
|
111
|
+
if (platform.inspect) {
|
|
112
|
+
try {
|
|
113
|
+
await platform.inspect(
|
|
114
|
+
{ env, cwd },
|
|
115
|
+
{ ok, warn, bad, note: (text) => out.write(` ${text}\n`) },
|
|
116
|
+
)
|
|
117
|
+
} catch (err) {
|
|
118
|
+
bad(failureText(err))
|
|
119
|
+
}
|
|
120
|
+
return failed ? 1 : 0
|
|
121
|
+
}
|
|
122
|
+
let settings = null
|
|
123
|
+
try {
|
|
124
|
+
settings = (await readSettings(platform.settingsFile(env))).settings
|
|
125
|
+
} catch (err) {
|
|
126
|
+
bad(failureText(err))
|
|
127
|
+
}
|
|
128
|
+
if (settings) {
|
|
129
|
+
if (platform.pluginActive(settings, env)) ok(`${platform.name} 的 kioku 插件已启用`)
|
|
130
|
+
else warn(`用户设置里没有启用 ${platform.name} 的 kioku 插件:${platform.pluginHint}`)
|
|
131
|
+
const by = platform.memory.disabledBy(settings, env)
|
|
132
|
+
const again = by ? await platform.memory.enabledBy(env, cwd) : null
|
|
133
|
+
if (again) {
|
|
134
|
+
warn(
|
|
135
|
+
`${platform.name} 的${platform.memory.name}在${by}里停用了,${again}又启用了它:要在那里一起改`,
|
|
136
|
+
)
|
|
137
|
+
} else if (by) ok(`${platform.name} 的${platform.memory.name}已停用(${by})`)
|
|
138
|
+
else {
|
|
139
|
+
warn(
|
|
140
|
+
`${platform.name} 的${platform.memory.name}还开着,会和 Kioku 各记一份:运行 kioku setup ${id} 停用它`,
|
|
141
|
+
)
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return failed ? 1 : 0
|
|
145
|
+
}
|