@kioku-memory/cli 0.6.1 → 0.6.2-edge.20261127111942.gcfb34f8
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/NOTICE +4 -0
- package/README.md +14 -6
- package/assets/plugins/zcode/.mcp.json +11 -0
- package/assets/plugins/zcode/.zcode-plugin/plugin.json +12 -0
- package/assets/plugins/zcode/README.md +48 -0
- package/assets/plugins/zcode/bin/kioku +36 -0
- package/assets/plugins/zcode/hooks/forward.mjs +350 -0
- package/assets/plugins/zcode/hooks/hooks.json +44 -0
- package/assets/plugins/zcode/hooks/mcp-stdio.mjs +261 -0
- package/assets/plugins/zcode/lib/command.mjs +158 -0
- package/assets/plugins/zcode/lib/config.mjs +44 -0
- package/assets/plugins/zcode/lib/http.mjs +102 -0
- package/assets/plugins/zcode/lib/kioku.mjs +58 -0
- package/assets/plugins/zcode/lib/lifecycle.mjs +163 -0
- package/assets/plugins/zcode/lib/mcp.mjs +171 -0
- package/assets/plugins/zcode/lib/profile.mjs +100 -0
- package/assets/plugins/zcode/lib/redact.mjs +91 -0
- package/assets/plugins/zcode/lib/run.mjs +406 -0
- package/assets/plugins/zcode/lib/text.mjs +14 -0
- package/assets/plugins/zcode/lib/usage.mjs +2 -0
- package/assets/plugins/zcode/marketplace.json +19 -0
- package/assets/plugins/zcode/package.json +7 -0
- package/assets/plugins/zcode/vitest.config.mjs +5 -0
- package/dist/index.mjs +379 -4
- package/package.json +1 -1
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
// ZCode 的 MCP stdio 桥接:从标准输入按行读取 JSON-RPC 2.0 消息,
|
|
2
|
+
// 转发到 Kioku 的 Streamable HTTP 端点(POST /v1/mcp),并将响应单行写回标准输出。
|
|
3
|
+
// 地址与访问密钥从 ~/.config/kioku/zcode.json 读取,绝不写入插件清单或命令行参数。
|
|
4
|
+
// 所有错误信息与标准错误日志均经过脱敏处理,绝不带出访问密钥。
|
|
5
|
+
|
|
6
|
+
import { realpathSync } from 'node:fs'
|
|
7
|
+
import { StringDecoder } from 'node:string_decoder'
|
|
8
|
+
import { fileURLToPath } from 'node:url'
|
|
9
|
+
|
|
10
|
+
import {
|
|
11
|
+
failureText,
|
|
12
|
+
fetchFailure,
|
|
13
|
+
isRedirect,
|
|
14
|
+
jsonOrNull,
|
|
15
|
+
KeyRejected,
|
|
16
|
+
keyFormatError,
|
|
17
|
+
KiokuFailure,
|
|
18
|
+
redirectError,
|
|
19
|
+
rejectionOf,
|
|
20
|
+
} from '../lib/http.mjs'
|
|
21
|
+
import { readProfile, serverUrlProblem } from '../lib/profile.mjs'
|
|
22
|
+
import { plain } from '../lib/text.mjs'
|
|
23
|
+
|
|
24
|
+
const DEFAULT_TIMEOUT_MS = 30_000
|
|
25
|
+
const LOGIN_HINT = '运行 kioku login zcode(没有 kioku 命令时用 npx @kioku-memory/cli login zcode)'
|
|
26
|
+
|
|
27
|
+
async function resolveMcpConfig(env) {
|
|
28
|
+
const profile = await readProfile('zcode', env)
|
|
29
|
+
if (!profile) {
|
|
30
|
+
throw new KiokuFailure(`Kioku 尚未配置服务地址和访问密钥:${LOGIN_HINT}`)
|
|
31
|
+
}
|
|
32
|
+
const problem = serverUrlProblem(profile.url) ?? keyFormatError(profile.key)
|
|
33
|
+
if (problem) throw new KiokuFailure(problem)
|
|
34
|
+
return { url: profile.url, key: profile.key }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function extractPayloads(text, contentType) {
|
|
38
|
+
if (!text.trim()) return []
|
|
39
|
+
if (!contentType.toLowerCase().includes('text/event-stream')) return [text]
|
|
40
|
+
const events = []
|
|
41
|
+
let current = []
|
|
42
|
+
for (const rawLine of text.split(/\r?\n/)) {
|
|
43
|
+
if (rawLine === '') {
|
|
44
|
+
if (current.length) {
|
|
45
|
+
events.push(current.join('\n'))
|
|
46
|
+
current = []
|
|
47
|
+
}
|
|
48
|
+
continue
|
|
49
|
+
}
|
|
50
|
+
if (rawLine.startsWith('data:')) current.push(rawLine.slice(5).trimStart())
|
|
51
|
+
}
|
|
52
|
+
if (current.length) events.push(current.join('\n'))
|
|
53
|
+
return events.filter((chunk) => chunk.trim() && chunk.trim() !== '[DONE]')
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function redactKey(text, key) {
|
|
57
|
+
const raw = key ? String(text).split(key).join('***') : String(text)
|
|
58
|
+
return plain(raw)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function writeJsonRpc(out, payload) {
|
|
62
|
+
out.write(`${JSON.stringify(payload)}\n`)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function errorPayload(id, message, key) {
|
|
66
|
+
return {
|
|
67
|
+
jsonrpc: '2.0',
|
|
68
|
+
id,
|
|
69
|
+
error: { code: -32000, message: redactKey(message, key) || 'Kioku MCP 请求失败' },
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async function forwardMessage(msg, { env, fetchImpl, out, errOut, timeoutMs }) {
|
|
74
|
+
const hasId = Boolean(
|
|
75
|
+
msg && typeof msg === 'object' && Object.hasOwn(msg, 'id') && msg.id !== undefined,
|
|
76
|
+
)
|
|
77
|
+
let config
|
|
78
|
+
try {
|
|
79
|
+
config = await resolveMcpConfig(env)
|
|
80
|
+
} catch (err) {
|
|
81
|
+
const reason = failureText(err)
|
|
82
|
+
errOut.write(`Kioku MCP 未生效:${reason}\n`)
|
|
83
|
+
if (hasId) writeJsonRpc(out, errorPayload(msg.id, reason, ''))
|
|
84
|
+
return
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
let res
|
|
88
|
+
let text
|
|
89
|
+
try {
|
|
90
|
+
res = await fetchImpl(`${config.url}/v1/mcp`, {
|
|
91
|
+
method: 'POST',
|
|
92
|
+
headers: {
|
|
93
|
+
'content-type': 'application/json',
|
|
94
|
+
accept: 'application/json, text/event-stream',
|
|
95
|
+
authorization: `Bearer ${config.key}`,
|
|
96
|
+
},
|
|
97
|
+
body: JSON.stringify(msg),
|
|
98
|
+
redirect: 'manual',
|
|
99
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
100
|
+
})
|
|
101
|
+
text = await res.text()
|
|
102
|
+
} catch (err) {
|
|
103
|
+
const reason = fetchFailure(err, timeoutMs)
|
|
104
|
+
errOut.write(`Kioku MCP 请求失败:${reason}\n`)
|
|
105
|
+
if (hasId) writeJsonRpc(out, errorPayload(msg.id, reason, config.key))
|
|
106
|
+
return
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
if (isRedirect(res.status)) {
|
|
110
|
+
const reason = redirectError(res.status, res.headers.get('location'), config.url)
|
|
111
|
+
errOut.write(`Kioku MCP 请求失败:${reason}\n`)
|
|
112
|
+
if (hasId) writeJsonRpc(out, errorPayload(msg.id, reason, config.key))
|
|
113
|
+
return
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const rejected = res.ok ? null : rejectionOf(res.status, jsonOrNull(text))
|
|
117
|
+
if (rejected) {
|
|
118
|
+
const reason =
|
|
119
|
+
rejected instanceof KeyRejected
|
|
120
|
+
? `${rejected.message}:${LOGIN_HINT}重新授权`
|
|
121
|
+
: rejected.message
|
|
122
|
+
errOut.write(`Kioku MCP 未生效:${reason}\n`)
|
|
123
|
+
if (hasId) writeJsonRpc(out, errorPayload(msg.id, reason, config.key))
|
|
124
|
+
return
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
if (!res.ok) {
|
|
128
|
+
const reason = `Kioku 返回 HTTP ${res.status}`
|
|
129
|
+
errOut.write(`Kioku MCP 请求失败:${reason}\n`)
|
|
130
|
+
if (hasId) writeJsonRpc(out, errorPayload(msg.id, reason, config.key))
|
|
131
|
+
return
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
if (!hasId) return
|
|
135
|
+
|
|
136
|
+
const payloads = extractPayloads(text, res.headers.get('content-type') ?? '')
|
|
137
|
+
let wrote = false
|
|
138
|
+
for (const chunk of payloads) {
|
|
139
|
+
let parsed
|
|
140
|
+
try {
|
|
141
|
+
parsed = JSON.parse(chunk)
|
|
142
|
+
} catch {
|
|
143
|
+
continue
|
|
144
|
+
}
|
|
145
|
+
if (parsed && typeof parsed === 'object') {
|
|
146
|
+
writeJsonRpc(out, parsed)
|
|
147
|
+
wrote = true
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
if (!wrote) {
|
|
151
|
+
const reason = 'Kioku 返回的 MCP 响应格式不对'
|
|
152
|
+
errOut.write(`Kioku MCP 请求失败:${reason}\n`)
|
|
153
|
+
writeJsonRpc(out, errorPayload(msg.id, reason, config.key))
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export async function runBridge({
|
|
158
|
+
stdin = process.stdin,
|
|
159
|
+
stdout = process.stdout,
|
|
160
|
+
stderr = process.stderr,
|
|
161
|
+
env = process.env,
|
|
162
|
+
fetchImpl = fetch,
|
|
163
|
+
timeoutMs = DEFAULT_TIMEOUT_MS,
|
|
164
|
+
} = {}) {
|
|
165
|
+
const decoder = new StringDecoder('utf8')
|
|
166
|
+
let buffer = ''
|
|
167
|
+
let queue = Promise.resolve()
|
|
168
|
+
|
|
169
|
+
const handleLine = (rawLine) => {
|
|
170
|
+
const line = rawLine.trim()
|
|
171
|
+
if (!line) return
|
|
172
|
+
let msg
|
|
173
|
+
try {
|
|
174
|
+
msg = JSON.parse(line)
|
|
175
|
+
} catch {
|
|
176
|
+
queue = queue.then(() =>
|
|
177
|
+
writeJsonRpc(stdout, {
|
|
178
|
+
jsonrpc: '2.0',
|
|
179
|
+
id: null,
|
|
180
|
+
error: { code: -32700, message: 'Parse error' },
|
|
181
|
+
}),
|
|
182
|
+
)
|
|
183
|
+
return
|
|
184
|
+
}
|
|
185
|
+
if (Array.isArray(msg) && msg.length === 0) {
|
|
186
|
+
queue = queue.then(() =>
|
|
187
|
+
writeJsonRpc(stdout, {
|
|
188
|
+
jsonrpc: '2.0',
|
|
189
|
+
id: null,
|
|
190
|
+
error: { code: -32600, message: 'Invalid Request' },
|
|
191
|
+
}),
|
|
192
|
+
)
|
|
193
|
+
return
|
|
194
|
+
}
|
|
195
|
+
const items = Array.isArray(msg) ? msg : [msg]
|
|
196
|
+
queue = queue.then(async () => {
|
|
197
|
+
for (const item of items) {
|
|
198
|
+
if (!item || typeof item !== 'object' || Array.isArray(item)) {
|
|
199
|
+
writeJsonRpc(stdout, {
|
|
200
|
+
jsonrpc: '2.0',
|
|
201
|
+
id: null,
|
|
202
|
+
error: { code: -32600, message: 'Invalid Request' },
|
|
203
|
+
})
|
|
204
|
+
continue
|
|
205
|
+
}
|
|
206
|
+
try {
|
|
207
|
+
await forwardMessage(item, { env, fetchImpl, out: stdout, errOut: stderr, timeoutMs })
|
|
208
|
+
} catch (err) {
|
|
209
|
+
const reason = failureText(err)
|
|
210
|
+
stderr.write(`Kioku MCP 请求失败:${reason}\n`)
|
|
211
|
+
if (Object.hasOwn(item, 'id') && item.id !== undefined) {
|
|
212
|
+
writeJsonRpc(stdout, errorPayload(item.id, reason, ''))
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
})
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
await new Promise((resolve) => {
|
|
220
|
+
stdin.on('data', (chunk) => {
|
|
221
|
+
buffer += typeof chunk === 'string' ? chunk : decoder.write(chunk)
|
|
222
|
+
for (;;) {
|
|
223
|
+
const nl = buffer.indexOf('\n')
|
|
224
|
+
if (nl === -1) break
|
|
225
|
+
const line = buffer.slice(0, nl)
|
|
226
|
+
buffer = buffer.slice(nl + 1)
|
|
227
|
+
handleLine(line)
|
|
228
|
+
}
|
|
229
|
+
})
|
|
230
|
+
stdin.once('end', () => {
|
|
231
|
+
buffer += decoder.end()
|
|
232
|
+
if (buffer.trim()) handleLine(buffer)
|
|
233
|
+
resolve()
|
|
234
|
+
})
|
|
235
|
+
stdin.once('error', () => resolve())
|
|
236
|
+
})
|
|
237
|
+
|
|
238
|
+
await queue
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
const isMain = () => {
|
|
242
|
+
const arg = process.argv[1]
|
|
243
|
+
if (!arg) return false
|
|
244
|
+
try {
|
|
245
|
+
return realpathSync(fileURLToPath(import.meta.url)) === realpathSync(arg)
|
|
246
|
+
} catch {
|
|
247
|
+
return false
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
if (isMain()) {
|
|
252
|
+
for (const stream of [process.stdout, process.stderr]) {
|
|
253
|
+
stream.on('error', (err) => {
|
|
254
|
+
if (!err || err.code !== 'EPIPE') throw err
|
|
255
|
+
})
|
|
256
|
+
}
|
|
257
|
+
runBridge().catch((err) => {
|
|
258
|
+
process.stderr.write(`Kioku MCP 桥接异常:${failureText(err)}\n`)
|
|
259
|
+
process.exitCode = 1
|
|
260
|
+
})
|
|
261
|
+
}
|
|
@@ -0,0 +1,158 @@
|
|
|
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 { accessSync, constants, statSync } from 'node:fs'
|
|
9
|
+
import { join, win32 } from 'node:path'
|
|
10
|
+
|
|
11
|
+
import { KiokuFailure } from './http.mjs'
|
|
12
|
+
|
|
13
|
+
const WINDOWS_APPS_STUB = /[\\/]Microsoft[\\/]WindowsApps[\\/][^\\/]+$/i
|
|
14
|
+
|
|
15
|
+
const isFile = (file) => {
|
|
16
|
+
try {
|
|
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
|
|
22
|
+
} catch {
|
|
23
|
+
return false
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Windows 的环境变量名不分大小写。同一个名字写了几种大小写时(Path 与 PATH),
|
|
28
|
+
// 取排序后的第一个:Node 把环境交给子进程时也是这样取的,两边看到的要是同一个
|
|
29
|
+
export function envValue(env, name) {
|
|
30
|
+
const key = Object.keys(env)
|
|
31
|
+
.filter((item) => item.toLowerCase() === name.toLowerCase())
|
|
32
|
+
.sort()[0]
|
|
33
|
+
return key === undefined ? undefined : env[key]
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Windows 上一个命令的完整路径;找不到为 null。名字里带目录时只看这个位置,否则在 PATH 里逐个目录找。
|
|
37
|
+
// 名字没写扩展名时只按 PATHEXT 补上扩展名找,不找原样的名字:npm 在 .cmd 旁边还放着一个同名、
|
|
38
|
+
// 没有扩展名的脚本(给 sh 用的),Windows 起不了它
|
|
39
|
+
export function findCommand(name, env, { exists = isFile } = {}) {
|
|
40
|
+
if (typeof name !== 'string' || !name) return null
|
|
41
|
+
const extensions = (envValue(env, 'PATHEXT') || '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean)
|
|
42
|
+
const suffixes = win32.extname(name) ? ['', ...extensions] : extensions
|
|
43
|
+
const dirs = /[\\/]/.test(name)
|
|
44
|
+
? ['']
|
|
45
|
+
: (envValue(env, 'PATH') ?? '')
|
|
46
|
+
.split(win32.delimiter)
|
|
47
|
+
// 带空格的目录有人会加上引号
|
|
48
|
+
.map((dir) => dir.replace(/^"(.*)"$/, '$1'))
|
|
49
|
+
.filter(Boolean)
|
|
50
|
+
for (const dir of dirs) {
|
|
51
|
+
for (const suffix of suffixes) {
|
|
52
|
+
const file = (dir ? win32.join(dir, name) : name) + suffix
|
|
53
|
+
if (exists(file)) return file
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return null
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// PATH 里有没有这个命令(向导的面板用来看平台装没装)。Windows 上照 findCommand 的规则找;
|
|
60
|
+
// 别的系统上找能执行的普通文件
|
|
61
|
+
export function hasCommand(name, env, { platform = process.platform } = {}) {
|
|
62
|
+
if (platform === 'win32') return findCommand(name, env) !== null
|
|
63
|
+
if (typeof name !== 'string' || !name) return false
|
|
64
|
+
const dirs = /\//.test(name) ? [''] : (envValue(env, 'PATH') ?? '').split(':').filter(Boolean)
|
|
65
|
+
return dirs.some((dir) => {
|
|
66
|
+
const file = dir ? join(dir, name) : name
|
|
67
|
+
try {
|
|
68
|
+
accessSync(file, constants.X_OK)
|
|
69
|
+
return statSync(file).isFile()
|
|
70
|
+
} catch {
|
|
71
|
+
return false
|
|
72
|
+
}
|
|
73
|
+
})
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// cmd.exe 认作有特殊含义的字符
|
|
77
|
+
const META = /([()\][%!^"`<>&|;, *?])/g
|
|
78
|
+
|
|
79
|
+
// 一个参数在 cmd.exe 的命令行里的写法:先按 Windows 程序解析参数的规则加引号、处理反斜杠与引号,
|
|
80
|
+
// 再给 cmd.exe 自己的特殊字符加 ^。经 node_modules/.bin 里的 .cmd 转一道的要转义两遍(它里面又解析一次)
|
|
81
|
+
function escapeArgument(value, twice) {
|
|
82
|
+
let arg = String(value)
|
|
83
|
+
arg = arg.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"')
|
|
84
|
+
arg = arg.replace(/(?=(\\+?)?)\1$/, '$1$1')
|
|
85
|
+
arg = `"${arg}"`.replace(META, '^$1')
|
|
86
|
+
return twice ? arg.replace(META, '^$1') : arg
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// 怎么起这个命令:{ file, args, options, shell },交给 spawn、execFile;Windows 上找不到这个命令时为 null。
|
|
90
|
+
// shell 为真表示中间隔着一层 cmd.exe,结束它要用 killTree。别的系统上原样返回,找不到由系统报 ENOENT
|
|
91
|
+
export function launch(name, args, env, { platform = process.platform, exists } = {}) {
|
|
92
|
+
if (platform !== 'win32') return { file: name, args, options: {}, shell: false }
|
|
93
|
+
const file = findCommand(name, env, { exists })
|
|
94
|
+
if (!file) return null
|
|
95
|
+
if (!/\.(cmd|bat)$/i.test(file)) return { file, args, options: {}, shell: false }
|
|
96
|
+
// cmd.exe 把换行当成一行命令的结尾,后面的参数会悄悄丢掉:不起
|
|
97
|
+
if ([file, ...args].some((item) => /[\r\n]/.test(String(item)))) {
|
|
98
|
+
throw new KiokuFailure('参数里有换行,经 cmd.exe 起的命令收不到完整的参数')
|
|
99
|
+
}
|
|
100
|
+
const twice = /node_modules[\\/]\.bin[\\/][^\\/]+\.cmd$/i.test(file)
|
|
101
|
+
const line = [file.replace(META, '^$1'), ...args.map((arg) => escapeArgument(arg, twice))]
|
|
102
|
+
return {
|
|
103
|
+
file: envValue(env, 'ComSpec') || 'cmd.exe',
|
|
104
|
+
// /d 不跑注册表里的自动命令,/s 加外层引号让整行原样交给 /c
|
|
105
|
+
args: ['/d', '/s', '/c', `"${line.join(' ')}"`],
|
|
106
|
+
// 这一行已经按 cmd.exe 的规则写好了,不让 Node 再加一层引号
|
|
107
|
+
options: { windowsVerbatimArguments: true },
|
|
108
|
+
shell: true,
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// 结束一个起好的命令。隔着 cmd.exe 时只结束它的话,真正的命令还活着、还占着输出的管道,
|
|
113
|
+
// 所以连它下面的进程一起结束(Windows 上没有信号可转,只能强行结束)
|
|
114
|
+
export function killTree(child, signal, { shell, platform = process.platform } = {}) {
|
|
115
|
+
if (platform !== 'win32' || !shell || child.pid === undefined) return child.kill(signal)
|
|
116
|
+
try {
|
|
117
|
+
spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' }).on(
|
|
118
|
+
'error',
|
|
119
|
+
() => child.kill(),
|
|
120
|
+
)
|
|
121
|
+
return true
|
|
122
|
+
} catch {
|
|
123
|
+
return child.kill()
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// 跑一个命令到结束,收下它的输出:{ found: false }(没有这个命令),
|
|
128
|
+
// 或者 { found: true, ok, stdout, output }(output 是两路输出合在一起,只用来认是哪种失败)。
|
|
129
|
+
// 超过时限就结束它(连同它下面的进程),算失败。不抛错
|
|
130
|
+
export function capture(name, args, env, { timeout, maxBuffer = 8 * 1024 * 1024 } = {}) {
|
|
131
|
+
let run
|
|
132
|
+
try {
|
|
133
|
+
run = launch(name, args, env)
|
|
134
|
+
} catch {
|
|
135
|
+
return Promise.resolve({ found: true, ok: false, stdout: '', output: '' })
|
|
136
|
+
}
|
|
137
|
+
if (!run) return Promise.resolve({ found: false })
|
|
138
|
+
return new Promise((resolve) => {
|
|
139
|
+
let timer
|
|
140
|
+
const child = execFile(
|
|
141
|
+
run.file,
|
|
142
|
+
run.args,
|
|
143
|
+
{ env, maxBuffer, ...run.options },
|
|
144
|
+
(err, stdout, stderr) => {
|
|
145
|
+
clearTimeout(timer)
|
|
146
|
+
if (err?.code === 'ENOENT') resolve({ found: false })
|
|
147
|
+
else {
|
|
148
|
+
const out = String(stdout ?? '')
|
|
149
|
+
resolve({ found: true, ok: !err, stdout: out, output: `${out}\n${stderr ?? ''}` })
|
|
150
|
+
}
|
|
151
|
+
},
|
|
152
|
+
)
|
|
153
|
+
if (timeout) {
|
|
154
|
+
timer = setTimeout(() => killTree(child, 'SIGTERM', { shell: run.shell }), timeout)
|
|
155
|
+
timer.unref?.()
|
|
156
|
+
}
|
|
157
|
+
})
|
|
158
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// kioku 命令的地址与访问密钥:从环境变量与访问密钥文件读
|
|
2
|
+
|
|
3
|
+
import { readFile, utimes } from 'node:fs/promises'
|
|
4
|
+
|
|
5
|
+
import { errorKind, keyFormatError, KiokuFailure } from './http.mjs'
|
|
6
|
+
import { serverUrlProblem } from './profile.mjs'
|
|
7
|
+
|
|
8
|
+
const NOT_CONFIGURED =
|
|
9
|
+
'缺少 Kioku 的地址或访问密钥:在 Claude Code 里启用 kioku 插件、填好配置后新开会话,或者设置 KIOKU_SERVER_URL 与 KIOKU_API_KEY'
|
|
10
|
+
|
|
11
|
+
// 地址或访问密钥根本没有配(区别于配了但不对)
|
|
12
|
+
export class NotConfigured extends KiokuFailure {}
|
|
13
|
+
|
|
14
|
+
// 地址与访问密钥。访问密钥先读插件在会话开始时配好的 KIOKU_API_KEY_FILE,读不到再用 KIOKU_API_KEY;
|
|
15
|
+
// 两样都没有才报错,报错只写文件的位置与错误类别
|
|
16
|
+
export async function loadConfig(env) {
|
|
17
|
+
const url = (env.KIOKU_SERVER_URL ?? '').trim().replace(/\/+$/, '')
|
|
18
|
+
const file = env.KIOKU_API_KEY_FILE
|
|
19
|
+
let key = ''
|
|
20
|
+
let fileProblem
|
|
21
|
+
if (file) {
|
|
22
|
+
try {
|
|
23
|
+
key = (await readFile(file, 'utf8')).trim()
|
|
24
|
+
if (!key) fileProblem = '文件是空的'
|
|
25
|
+
} catch (err) {
|
|
26
|
+
fileProblem = errorKind(err)
|
|
27
|
+
}
|
|
28
|
+
// 用的时候更新修改时间:会话开始时会删掉很久没用过的访问密钥文件
|
|
29
|
+
if (key) await utimes(file, new Date(), new Date()).catch(() => {})
|
|
30
|
+
}
|
|
31
|
+
if (!key) key = (env.KIOKU_API_KEY ?? '').trim()
|
|
32
|
+
if (!url) throw new NotConfigured(NOT_CONFIGURED)
|
|
33
|
+
if (!key) {
|
|
34
|
+
if (!fileProblem) throw new NotConfigured(NOT_CONFIGURED)
|
|
35
|
+
throw new KiokuFailure(
|
|
36
|
+
`无法读取访问密钥文件 ${file}(${fileProblem}):新开会话,或者设置 KIOKU_API_KEY`,
|
|
37
|
+
)
|
|
38
|
+
}
|
|
39
|
+
const urlProblem = serverUrlProblem(url)
|
|
40
|
+
if (urlProblem) throw new KiokuFailure(urlProblem.replace(/^服务地址/, 'KIOKU_SERVER_URL '))
|
|
41
|
+
const problem = keyFormatError(key)
|
|
42
|
+
if (problem) throw new KiokuFailure(problem)
|
|
43
|
+
return { url, key }
|
|
44
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
// 钩子与 kioku 命令共用的访问密钥检查与报错。报错只给插件自己写的文字或错误类别:
|
|
2
|
+
// fetch 的报错会带上整个 Authorization 请求头,响应解析失败的文字会带上响应的开头
|
|
3
|
+
|
|
4
|
+
// 访问密钥只能是可见的 ASCII 字符:别的字符放不进请求头,fetch 报错时会把整个请求头写进错误文字
|
|
5
|
+
const KEY = /^[\x21-\x7e]+$/
|
|
6
|
+
// 错误码(ECONNREFUSED、UND_ERR_SOCKET 这类)与错误类名(TypeError 这类)的样子
|
|
7
|
+
const CODE = /^[A-Z][A-Z0-9_]*$/
|
|
8
|
+
const NAME = /^[A-Z][A-Za-z]*$/
|
|
9
|
+
|
|
10
|
+
// 文字由插件自己写、不含值和访问密钥的失败,可以原样打印
|
|
11
|
+
export class KiokuFailure extends Error {}
|
|
12
|
+
|
|
13
|
+
// 访问密钥的格式不对时返回原因,否则为 null
|
|
14
|
+
export function keyFormatError(key) {
|
|
15
|
+
return KEY.test(key) ? null : '访问密钥的格式不对:只能是可见的 ASCII 字符,不能有空白'
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// 错误的类别:只取 code 或 name,不取文字
|
|
19
|
+
export function errorKind(err) {
|
|
20
|
+
if (typeof err?.code === 'string' && CODE.test(err.code)) return err.code
|
|
21
|
+
if (typeof err?.name === 'string' && NAME.test(err.name)) return err.name
|
|
22
|
+
return '未知错误'
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// fetch 失败的原因:超时,或者连不上(附 cause 的错误码)
|
|
26
|
+
export function fetchFailure(err, timeoutMs) {
|
|
27
|
+
if (err?.name === 'TimeoutError' || err?.name === 'AbortError') {
|
|
28
|
+
return `连接 Kioku 超时(${timeoutMs / 1000} 秒)`
|
|
29
|
+
}
|
|
30
|
+
const code = err?.cause?.code
|
|
31
|
+
return typeof code === 'string' && CODE.test(code)
|
|
32
|
+
? `无法连接 Kioku(${code})`
|
|
33
|
+
: '无法连接 Kioku'
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// 收到跳转(3xx)时的报错:说明要把地址改成跳转之后的地址。请求都不跟着跳转走,访问密钥只发给配置的地址;
|
|
37
|
+
// 跳转目标只给协议与主机,路径与查询参数里可能带着令牌;跳到同一个主机、或者没给目标时不举例
|
|
38
|
+
export function redirectError(status, location, url) {
|
|
39
|
+
let origin
|
|
40
|
+
try {
|
|
41
|
+
const target = new URL(location ?? '', `${url}/`)
|
|
42
|
+
const web = target.protocol === 'https:' || target.protocol === 'http:'
|
|
43
|
+
if (web && target.origin !== new URL(url).origin) origin = target.origin
|
|
44
|
+
} catch {
|
|
45
|
+
// 跳转目标解析不了时不举例
|
|
46
|
+
}
|
|
47
|
+
return `Kioku 返回了跳转(${status}),把地址改成跳转之后的地址${origin ? `(例如 ${origin})` : ''}`
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function isRedirect(status) {
|
|
51
|
+
return status >= 300 && status < 400
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// 要打印的失败原因:插件自己写的原样给出,别的只给类别
|
|
55
|
+
export function failureText(err) {
|
|
56
|
+
return err instanceof KiokuFailure ? err.message : errorKind(err)
|
|
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
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// 插件目录里放着的精简 kioku 入口:只实现 kioku run(插件启用期间放在 PATH 里给 Bash 工具用)。
|
|
2
|
+
// 向导、接入、检查、日常记忆读写等完整命令行在 npm 包 @kioku-memory/cli
|
|
3
|
+
|
|
4
|
+
import { parseRunArgs, run, USAGE, UsageError } from './run.mjs'
|
|
5
|
+
|
|
6
|
+
export { parseRunArgs, run, USAGE, UsageError }
|
|
7
|
+
|
|
8
|
+
const OVERVIEW = `用法:kioku run -e 变量=<标识>[#<字段>] [-e …] [--purpose <用途>] -- <命令> [参数…]
|
|
9
|
+
|
|
10
|
+
插件目录内置的命令行入口仅包含 kioku run(向 Kioku 取凭据,放进环境变量并打码输出)。
|
|
11
|
+
向导、接入管理与记忆读写等完整功能见 @kioku-memory/cli:
|
|
12
|
+
|
|
13
|
+
npx @kioku-memory/cli
|
|
14
|
+
npm install -g @kioku-memory/cli
|
|
15
|
+
|
|
16
|
+
运行子命令用法:kioku run --help
|
|
17
|
+
`
|
|
18
|
+
|
|
19
|
+
const FULL_CLI_COMMANDS = new Set([
|
|
20
|
+
'connect',
|
|
21
|
+
'disconnect',
|
|
22
|
+
'migrate',
|
|
23
|
+
'upgrade',
|
|
24
|
+
'status',
|
|
25
|
+
'login',
|
|
26
|
+
'setup',
|
|
27
|
+
'install',
|
|
28
|
+
'doctor',
|
|
29
|
+
'clean',
|
|
30
|
+
'import',
|
|
31
|
+
'local',
|
|
32
|
+
'open',
|
|
33
|
+
'search',
|
|
34
|
+
'get',
|
|
35
|
+
'ls',
|
|
36
|
+
'add',
|
|
37
|
+
'edit',
|
|
38
|
+
'delete',
|
|
39
|
+
'rm',
|
|
40
|
+
'boot',
|
|
41
|
+
])
|
|
42
|
+
|
|
43
|
+
export async function main(argv) {
|
|
44
|
+
const [sub, ...rest] = argv
|
|
45
|
+
if (sub === '-h' || sub === '--help') {
|
|
46
|
+
process.stdout.write(OVERVIEW)
|
|
47
|
+
return 0
|
|
48
|
+
}
|
|
49
|
+
if (sub === 'run') return run(rest)
|
|
50
|
+
if (sub && FULL_CLI_COMMANDS.has(sub)) {
|
|
51
|
+
process.stderr.write(
|
|
52
|
+
`kioku:插件内置入口仅含 run 子命令;运行 npx @kioku-memory/cli ${sub}(或全局安装 @kioku-memory/cli)\n`,
|
|
53
|
+
)
|
|
54
|
+
return 2
|
|
55
|
+
}
|
|
56
|
+
process.stderr.write(sub === undefined ? OVERVIEW : `kioku:不认识的子命令 ${sub}\n\n${OVERVIEW}`)
|
|
57
|
+
return 2
|
|
58
|
+
}
|