@kioku-memory/cli 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +63 -23
  2. package/assets/plugins/agy/README.md +34 -0
  3. package/assets/plugins/agy/bin/kioku +36 -0
  4. package/assets/plugins/agy/hooks/forward.mjs +232 -0
  5. package/assets/plugins/agy/hooks.json +25 -0
  6. package/assets/plugins/agy/lib/kioku.mjs +53 -0
  7. package/{lib/kioku.mjs → assets/plugins/agy/lib/run.mjs} +4 -83
  8. package/assets/plugins/agy/package.json +7 -0
  9. package/assets/plugins/agy/plugin.json +6 -0
  10. package/assets/plugins/agy/vitest.config.mjs +5 -0
  11. package/assets/plugins/gemini/README.md +33 -0
  12. package/assets/plugins/gemini/bin/kioku +36 -0
  13. package/assets/plugins/gemini/gemini-extension.json +5 -0
  14. package/assets/plugins/gemini/hooks/forward.mjs +174 -0
  15. package/assets/plugins/gemini/hooks/hooks.json +43 -0
  16. package/assets/plugins/gemini/lib/command.mjs +152 -0
  17. package/assets/plugins/gemini/lib/config.mjs +50 -0
  18. package/assets/plugins/gemini/lib/http.mjs +57 -0
  19. package/assets/plugins/gemini/lib/kioku.mjs +53 -0
  20. package/assets/plugins/gemini/lib/lifecycle.mjs +128 -0
  21. package/assets/plugins/gemini/lib/mcp.mjs +142 -0
  22. package/assets/plugins/gemini/lib/profile.mjs +100 -0
  23. package/assets/plugins/gemini/lib/redact.mjs +91 -0
  24. package/assets/plugins/gemini/lib/run.mjs +372 -0
  25. package/assets/plugins/gemini/lib/text.mjs +14 -0
  26. package/assets/plugins/gemini/lib/usage.mjs +2 -0
  27. package/assets/plugins/gemini/package.json +7 -0
  28. package/assets/plugins/gemini/vitest.config.mjs +5 -0
  29. package/bin/kioku +16 -12
  30. package/dist/index.mjs +8846 -0
  31. package/package.json +14 -5
  32. package/lib/agy.mjs +0 -181
  33. package/lib/api.mjs +0 -38
  34. package/lib/clean.mjs +0 -96
  35. package/lib/codex.mjs +0 -320
  36. package/lib/conflicts.mjs +0 -1303
  37. package/lib/connect.mjs +0 -152
  38. package/lib/doctor.mjs +0 -158
  39. package/lib/dsh.mjs +0 -82
  40. package/lib/files.mjs +0 -92
  41. package/lib/gemini.mjs +0 -199
  42. package/lib/hermes.mjs +0 -276
  43. package/lib/import.mjs +0 -301
  44. package/lib/install.mjs +0 -196
  45. package/lib/local.mjs +0 -294
  46. package/lib/login.mjs +0 -359
  47. package/lib/openclaw.mjs +0 -256
  48. package/lib/opencode.mjs +0 -144
  49. package/lib/panel.mjs +0 -311
  50. package/lib/pi.mjs +0 -90
  51. package/lib/platforms.mjs +0 -297
  52. package/lib/prompts.mjs +0 -38
  53. package/lib/secret.mjs +0 -86
  54. package/lib/setup.mjs +0 -139
  55. package/lib/sources.mjs +0 -333
  56. package/lib/target.mjs +0 -62
  57. package/lib/wizard.mjs +0 -534
  58. /package/{lib → assets/plugins/agy/lib}/command.mjs +0 -0
  59. /package/{lib → assets/plugins/agy/lib}/config.mjs +0 -0
  60. /package/{lib → assets/plugins/agy/lib}/http.mjs +0 -0
  61. /package/{lib → assets/plugins/agy/lib}/lifecycle.mjs +0 -0
  62. /package/{lib → assets/plugins/agy/lib}/mcp.mjs +0 -0
  63. /package/{lib → assets/plugins/agy/lib}/profile.mjs +0 -0
  64. /package/{lib → assets/plugins/agy/lib}/redact.mjs +0 -0
  65. /package/{lib → assets/plugins/agy/lib}/text.mjs +0 -0
  66. /package/{lib → assets/plugins/agy/lib}/usage.mjs +0 -0
@@ -1,4 +1,4 @@
1
- // kioku 命令。kioku run 向 Kioku 取凭据的值,放进环境变量交给要跑的命令,命令的输出打过码再写出:
1
+ // kioku run:向 Kioku 取凭据的值,放进环境变量交给要跑的命令,命令的输出打过码再写出:
2
2
  // 命令行、对话记录与发给模型的内容里只有变量名。
3
3
  // 报错的文字都不带值和访问密钥:spawn 的参数错误会带出环境变量的值,fetch 的错误会带出请求头,
4
4
  // 所以这两处只取错误类别
@@ -7,13 +7,8 @@ import { spawn } from 'node:child_process'
7
7
  import { constants } from 'node:os'
8
8
  import { isatty } from 'node:tty'
9
9
 
10
- import { clean, CLEAN_USAGE } from './clean.mjs'
11
10
  import { killTree, launch } from './command.mjs'
12
11
  import { loadConfig } from './config.mjs'
13
- import { IMPORT_USAGE, importMemories } from './import.mjs'
14
- import { install, INSTALL_USAGE } from './install.mjs'
15
- import { login, LOGIN_USAGE } from './login.mjs'
16
- import { doctor, DOCTOR_USAGE } from './doctor.mjs'
17
12
  import {
18
13
  errorKind,
19
14
  failureText,
@@ -22,10 +17,8 @@ import {
22
17
  KiokuFailure,
23
18
  redirectError,
24
19
  } from './http.mjs'
25
- import { loadPrompts } from './prompts.mjs'
26
- import { setup, SETUP_USAGE } from './setup.mjs'
27
- import { UsageError } from './usage.mjs'
28
20
  import { createRedactor, MIN_REDACT_CHARS, redactable } from './redact.mjs'
21
+ import { UsageError } from './usage.mjs'
29
22
 
30
23
  // 等 Kioku 取值的上限(毫秒)
31
24
  const TIMEOUT = 15_000
@@ -40,7 +33,7 @@ const CONTROL = /\p{Cc}/u
40
33
  const KEY_VARIABLES = ['KIOKU_API_KEY', 'KIOKU_API_KEY_FILE']
41
34
  // 收到这些信号时转给命令。有终端时 SIGINT 除外:终端的 Ctrl-C 发给整个前台进程组,命令和 kioku 在同一个组里,
42
35
  // 已经收到了,再转一次就成了两次(有的工具连按两次会跳过清理);SIGINT 照样接住,kioku 才能等命令处理完。
43
- // 没有终端时(例如 Claude Code 的 Bash 工具)SIGINT 是单独发给 kioku 的,照样转发。
36
+ // 没有终端时(例如 Claude Code 的 Bash 工具)SIGINT 是单独发来的,照样转发。
44
37
  // 发给整个进程组的 SIGTERM、SIGHUP(没有终端时还有 SIGINT),命令会收到两次,这是已知的限制
45
38
  const SIGNALS = ['SIGINT', 'SIGTERM', 'SIGHUP']
46
39
  // 标准输入、输出或错误有一个是终端,就当作在终端里运行。用 isatty 查文件描述符,不碰 process.stdin:
@@ -337,7 +330,7 @@ function runCommand(command, args, env, values) {
337
330
  })
338
331
  }
339
332
 
340
- async function run(argv) {
333
+ export async function run(argv) {
341
334
  let options
342
335
  try {
343
336
  options = parseRunArgs(argv)
@@ -377,75 +370,3 @@ async function run(argv) {
377
370
  }
378
371
  return runCommand(command, args, env, values)
379
372
  }
380
-
381
- // 入口:返回退出码
382
- const OVERVIEW = `用法:kioku <子命令> [参数…]
383
-
384
- run 向 Kioku 取凭据的值,放进环境变量交给命令
385
- login 用浏览器授权签发访问密钥并配好这个平台
386
- setup 停用平台自带的长期记忆,由 Kioku 接管
387
- install 几个平台一起接入,访问密钥从环境变量读(给脚本用)
388
- doctor 检查地址、访问密钥与平台的配置
389
- clean 检测并卸载冲突的记忆工具(Lore 及常见记忆 MCP)
390
- import 把平台自带的本地长期记忆迁进 Kioku
391
-
392
- 在终端里不带参数运行 kioku 是交互式的向导:看各平台接到哪一步,按缺的一步步接上。
393
- 各子命令的说明:kioku <子命令> --help
394
- `
395
-
396
- const NO_WIZARD =
397
- '交互式的向导要 npm 上的 kioku(Node 20.12 以上):npm install -g @kioku-memory/cli\n'
398
-
399
- // 交互式的向导。插件目录里的 kioku 带不了交互库,装不到时打印用法并说明
400
- async function startWizard() {
401
- const ui = await loadPrompts()
402
- if (!ui) {
403
- process.stderr.write(`${OVERVIEW}\n${NO_WIZARD}`)
404
- return 2
405
- }
406
- const { barOut, wizard } = await import('./wizard.mjs')
407
- return wizard({ ui, env: process.env, cwd: process.cwd(), out: barOut(process.stdout) })
408
- }
409
-
410
- // 说明类的子命令:参数写错时打印原因与说明,以 2 退出;别的失败原因写到标准错误
411
- async function guarded(name, usage, fn, argv) {
412
- if (argv.includes('-h') || argv.includes('--help')) {
413
- process.stdout.write(usage)
414
- return 0
415
- }
416
- try {
417
- return await fn(argv)
418
- } catch (err) {
419
- if (err instanceof UsageError) {
420
- process.stderr.write(`kioku ${name}:${err.message}\n\n${usage}`)
421
- return 2
422
- }
423
- if (err instanceof KiokuFailure) {
424
- process.stderr.write(`kioku ${name}:${err.message}\n`)
425
- return 2
426
- }
427
- throw err
428
- }
429
- }
430
-
431
- // interactive:标准输入与输出都是终端时才进向导;管道、agent 的命令里照旧打印用法
432
- export async function main(
433
- argv,
434
- { interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY), wizard = startWizard } = {},
435
- ) {
436
- const [sub, ...rest] = argv
437
- if (sub === undefined && interactive) return wizard()
438
- if (sub === '-h' || sub === '--help') {
439
- process.stdout.write(OVERVIEW)
440
- return 0
441
- }
442
- if (sub === 'run') return run(rest)
443
- if (sub === 'login') return guarded('login', LOGIN_USAGE, login, rest)
444
- if (sub === 'setup') return guarded('setup', SETUP_USAGE, setup, rest)
445
- if (sub === 'install') return guarded('install', INSTALL_USAGE, install, rest)
446
- if (sub === 'doctor') return guarded('doctor', DOCTOR_USAGE, doctor, rest)
447
- if (sub === 'clean') return guarded('clean', CLEAN_USAGE, clean, rest)
448
- if (sub === 'import') return guarded('import', IMPORT_USAGE, importMemories, rest)
449
- process.stderr.write(sub === undefined ? OVERVIEW : `kioku:不认识的子命令 ${sub}\n\n${OVERVIEW}`)
450
- return 2
451
- }
@@ -0,0 +1,7 @@
1
+ {
2
+ "name": "@kioku-memory/plugin-agy",
3
+ "private": true,
4
+ "scripts": {
5
+ "test": "vitest run"
6
+ }
7
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "name": "kioku",
3
+ "description": "Kioku 长期记忆:会话开始注入启动加载,每轮输入注入召回候选,每轮结束后写入会话摘要",
4
+ "homepage": "https://github.com/lonelyman0108/kioku",
5
+ "repository": "https://github.com/lonelyman0108/kioku-plugins"
6
+ }
@@ -0,0 +1,5 @@
1
+ import { defineConfig } from 'vitest/config'
2
+
3
+ // 插件包没有自己的依赖目录,不指定的话会和别的包共用工作区根目录下的缓存,
4
+ // 并行跑测试时互相清理,偶尔启动失败
5
+ export default defineConfig({ cacheDir: 'node_modules/.vite' })
@@ -0,0 +1,33 @@
1
+ # Kioku 的 Gemini CLI 插件
2
+
3
+ 为 Gemini CLI 接入 Kioku 长期记忆:
4
+
5
+ - `SessionStart` 注入启动加载内容;
6
+ - `BeforeAgent` 根据当前输入注入召回候选;
7
+ - `AfterAgent` 在本轮结束后将对话提交 Kioku 生成会话摘要;
8
+ - 在 `~/.gemini/settings.json` 中自动写入 `mcpServers.kioku`(`httpUrl`)并把自带的 `save_memory` 工具加入 `excludeTools`。
9
+
10
+ ## 安装与配置
11
+
12
+ 先在 Kioku 管理界面的「应用」页建一个运行时是 `Gemini CLI`(`gemini`)的应用,然后:
13
+
14
+ ```bash
15
+ # 1. 配好服务地址、访问密钥、MCP 服务并停用自带 save_memory
16
+ npx @kioku-memory/cli setup gemini --server-url https://kioku.example.com
17
+
18
+ # 2. 链接此扩展启用生命周期钩子
19
+ git clone https://github.com/lonelyman0108/kioku-plugins
20
+ gemini extensions link kioku-plugins/plugins/gemini
21
+ ```
22
+
23
+ 或使用浏览器授权:
24
+
25
+ ```bash
26
+ npx @kioku-memory/cli login gemini --server-url https://kioku.example.com
27
+ ```
28
+
29
+ 检查配置:
30
+
31
+ ```bash
32
+ npx @kioku-memory/cli doctor gemini
33
+ ```
@@ -0,0 +1,36 @@
1
+ #!/usr/bin/env node
2
+ // kioku 命令的入口,实现在 ../lib/kioku.mjs。插件启用期间,Claude Code 把插件的 bin/ 加进 Bash 工具的 PATH。
3
+ // 没有扩展名的文件按 CommonJS 还是 ES 模块执行,取决于 Node 的版本与上层的 package.json,
4
+ // 所以这里只用两边都能用的写法:动态 import,位置从 process.argv[1] 推
5
+ const load = (name) =>
6
+ Promise.all([import('node:fs'), import('node:path'), import('node:url')]).then(
7
+ ([fs, path, url]) => {
8
+ const lib = path.join(path.dirname(fs.realpathSync(process.argv[1])), '..', 'lib')
9
+ return import(url.pathToFileURL(path.join(lib, name)).href)
10
+ },
11
+ )
12
+
13
+ // 输出被读的一方提前关掉(kioku doctor | head):之后的输出写不出去就算了,不抛一段堆栈;
14
+ // 手上的事照常做完、按它的结果退出(中途停下的话,写了一半的导入、配置会被当成成功)。别的写入错误照旧抛。
15
+ // run 不在此列:它转发命令的输出,自己处理这种情况
16
+ if (process.argv[2] !== 'run') {
17
+ for (const stream of [process.stdout, process.stderr]) {
18
+ stream.on('error', (err) => {
19
+ if (!err || err.code !== 'EPIPE') throw err
20
+ })
21
+ }
22
+ }
23
+
24
+ load('kioku.mjs')
25
+ .then((cli) => cli.main(process.argv.slice(2)))
26
+ .then((code) => {
27
+ process.exitCode = code
28
+ })
29
+ .catch((err) => {
30
+ process.exitCode = 2
31
+ // 只给错误类别:错误文字里可能带着环境变量的值。取不到共用的函数时只说一句固定的
32
+ return load('http.mjs').then(
33
+ ({ errorKind }) => process.stderr.write(`kioku:内部错误(${errorKind(err)})\n`),
34
+ () => process.stderr.write('kioku:内部错误\n'),
35
+ )
36
+ })
@@ -0,0 +1,5 @@
1
+ {
2
+ "name": "kioku",
3
+ "version": "0.1.0",
4
+ "description": "Kioku 长期记忆:会话开始注入启动加载,每轮输入注入召回候选,每轮结束后写入会话摘要"
5
+ }
@@ -0,0 +1,174 @@
1
+ // Gemini CLI 扩展钩子:把 SessionStart、BeforeAgent、AfterAgent 转发给 Kioku 的生命周期端点。
2
+ // 任何失败都以退出码 0 结束、不阻断会话,原因写到标准错误(不带访问密钥)。
3
+
4
+ import { randomUUID } from 'node:crypto'
5
+ import { mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'
6
+ import { join } from 'node:path'
7
+ import { pathToFileURL } from 'node:url'
8
+
9
+ import { failureText, KiokuFailure } from '../lib/http.mjs'
10
+ import {
11
+ clip,
12
+ contextOf,
13
+ MAX_PROMPT,
14
+ MAX_REPLY,
15
+ MAX_SESSION_ID,
16
+ Misconfigured,
17
+ postEvent,
18
+ projectOf,
19
+ TIMEOUTS,
20
+ } from '../lib/lifecycle.mjs'
21
+ import { profileDir, readProfile } from '../lib/profile.mjs'
22
+
23
+ const HOOK_EVENTS = { 'session.start': 'SessionStart', 'prompt.submit': 'BeforeAgent' }
24
+ const ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/
25
+ const PENDING_PREFIX = 'turn.'
26
+ const PENDING_MAX_AGE = 24 * 60 * 60 * 1000
27
+ const SETUP_HINT =
28
+ '运行 kioku setup gemini 配置(没有 kioku 命令时用 npx @kioku-memory/cli setup gemini)'
29
+
30
+ async function readStdin() {
31
+ const chunks = []
32
+ for await (const chunk of process.stdin) chunks.push(chunk)
33
+ return Buffer.concat(chunks).toString('utf8')
34
+ }
35
+
36
+ function writeContext(event, text) {
37
+ if (typeof text !== 'string' || !text) return
38
+ process.stdout.write(
39
+ JSON.stringify({
40
+ hookSpecificOutput: { hookEventName: HOOK_EVENTS[event], additionalContext: text },
41
+ }),
42
+ )
43
+ }
44
+
45
+ function pendingDir(env) {
46
+ return join(env.KIOKU_GEMINI_STATE || join(profileDir(env), 'gemini-state'), 'turns')
47
+ }
48
+
49
+ function pendingFile(env, sessionId) {
50
+ if (!ID.test(sessionId ?? '')) return null
51
+ return join(pendingDir(env), `${PENDING_PREFIX}${sessionId}.json`)
52
+ }
53
+
54
+ async function savePending(env, sessionId, prompt) {
55
+ const file = pendingFile(env, sessionId)
56
+ if (!file) return
57
+ await mkdir(pendingDir(env), { recursive: true, mode: 0o700 })
58
+ const temp = `${file}.${randomUUID()}.tmp`
59
+ try {
60
+ await writeFile(temp, JSON.stringify({ prompt }), { mode: 0o600, flag: 'wx' })
61
+ await rename(temp, file)
62
+ } catch (err) {
63
+ await rm(temp, { force: true }).catch(() => {})
64
+ throw err
65
+ }
66
+ }
67
+
68
+ async function takePending(env, sessionId) {
69
+ const file = pendingFile(env, sessionId)
70
+ if (!file) return null
71
+ try {
72
+ const { prompt } = JSON.parse(await readFile(file, 'utf8'))
73
+ return typeof prompt === 'string' && prompt ? prompt : null
74
+ } catch {
75
+ return null
76
+ } finally {
77
+ await rm(file, { force: true }).catch(() => {})
78
+ }
79
+ }
80
+
81
+ async function sweepPending(env) {
82
+ const dir = pendingDir(env)
83
+ const names = await readdir(dir).catch(() => [])
84
+ for (const name of names) {
85
+ if (!name.startsWith(PENDING_PREFIX)) continue
86
+ const file = join(dir, name)
87
+ const age = Date.now() - ((await stat(file).catch(() => null))?.mtimeMs ?? Date.now())
88
+ if (age > PENDING_MAX_AGE) await rm(file, { force: true }).catch(() => {})
89
+ }
90
+ }
91
+
92
+ export async function forwardGeminiEvent(event, rawStdin, env = process.env) {
93
+ const timeout = TIMEOUTS[event]
94
+ if (!timeout) throw new KiokuFailure(`未知事件 ${event}`)
95
+ let input = {}
96
+ try {
97
+ input = JSON.parse(rawStdin || '{}')
98
+ } catch {
99
+ // 非 JSON 时按空输入处理,避免阻断用户回合
100
+ }
101
+ if (event !== 'turn.end') await sweepPending(env)
102
+
103
+ let profile
104
+ try {
105
+ profile = await readProfile('gemini', env)
106
+ } catch (err) {
107
+ throw err instanceof KiokuFailure ? new Misconfigured(err.message, 'profile') : err
108
+ }
109
+ if (!profile) {
110
+ if (event === 'session.start') {
111
+ return `Kioku 插件还没有配置服务地址和访问密钥,长期记忆不可用:${SETUP_HINT}。`
112
+ }
113
+ return null
114
+ }
115
+
116
+ const { url: base, key } = profile
117
+ const sessionId =
118
+ typeof input.session_id === 'string' && input.session_id
119
+ ? input.session_id.slice(0, MAX_SESSION_ID)
120
+ : undefined
121
+ const body = { event, ...(sessionId ? { sessionId } : {}) }
122
+
123
+ if (event === 'turn.end') {
124
+ if (input.stop_hook_active === true) return null
125
+ const direct = typeof input.prompt === 'string' ? input.prompt.trim() : ''
126
+ const user = direct || (await takePending(env, sessionId))
127
+ const reply =
128
+ typeof input.prompt_response === 'string'
129
+ ? input.prompt_response
130
+ : typeof input.last_assistant_message === 'string'
131
+ ? input.last_assistant_message
132
+ : ''
133
+ if (!sessionId || !user) return null
134
+ body.user = clip(user, MAX_PROMPT)
135
+ body.reply = clip(reply.trim(), MAX_REPLY)
136
+ await postEvent(base, key, body, timeout)
137
+ return null
138
+ }
139
+
140
+ if (event === 'session.start') {
141
+ const cwd = typeof input.cwd === 'string' && input.cwd ? input.cwd : process.cwd()
142
+ const project = projectOf(cwd)
143
+ if (Object.keys(project).length) body.project = project
144
+ }
145
+
146
+ if (event === 'prompt.submit') {
147
+ const prompt = typeof input.prompt === 'string' ? input.prompt.trim() : ''
148
+ if (!prompt) return null
149
+ body.prompt = clip(prompt, MAX_PROMPT)
150
+ await savePending(env, sessionId, body.prompt).catch(() => {})
151
+ }
152
+
153
+ const res = await postEvent(base, key, body, timeout)
154
+ const { hostOutput } = await res.json()
155
+ return contextOf(hostOutput) ?? null
156
+ }
157
+
158
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
159
+ const event = process.argv[2]
160
+ readStdin()
161
+ .then((raw) => forwardGeminiEvent(event, raw, process.env))
162
+ .then((text) => {
163
+ if (text && HOOK_EVENTS[event]) writeContext(event, text)
164
+ })
165
+ .catch((err) => {
166
+ if (event === 'session.start' && err instanceof Misconfigured) {
167
+ writeContext(
168
+ event,
169
+ `Kioku 插件的配置无法使用,长期记忆不可用:${err.message}。${SETUP_HINT}。`,
170
+ )
171
+ }
172
+ process.stderr.write(`Kioku ${event ?? ''} 未生效:${failureText(err)}\n`)
173
+ })
174
+ }
@@ -0,0 +1,43 @@
1
+ {
2
+ "hooks": {
3
+ "SessionStart": [
4
+ {
5
+ "matcher": "*",
6
+ "hooks": [
7
+ {
8
+ "name": "kioku-session-start",
9
+ "type": "command",
10
+ "command": "node \"${extensionPath}/hooks/forward.mjs\" session.start",
11
+ "timeout": 10000
12
+ }
13
+ ]
14
+ }
15
+ ],
16
+ "BeforeAgent": [
17
+ {
18
+ "matcher": "*",
19
+ "hooks": [
20
+ {
21
+ "name": "kioku-before-agent",
22
+ "type": "command",
23
+ "command": "node \"${extensionPath}/hooks/forward.mjs\" prompt.submit",
24
+ "timeout": 10000
25
+ }
26
+ ]
27
+ }
28
+ ],
29
+ "AfterAgent": [
30
+ {
31
+ "matcher": "*",
32
+ "hooks": [
33
+ {
34
+ "name": "kioku-after-agent",
35
+ "type": "command",
36
+ "command": "node \"${extensionPath}/hooks/forward.mjs\" turn.end",
37
+ "timeout": 10000
38
+ }
39
+ ]
40
+ }
41
+ ]
42
+ }
43
+ }
@@ -0,0 +1,152 @@
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 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
+ // PATH 里有没有这个命令(向导的面板用来看平台装没装)。Windows 上照 findCommand 的规则找;
54
+ // 别的系统上找能执行的普通文件
55
+ export function hasCommand(name, env, { platform = process.platform } = {}) {
56
+ if (platform === 'win32') return findCommand(name, env) !== null
57
+ if (typeof name !== 'string' || !name) return false
58
+ const dirs = /\//.test(name) ? [''] : (envValue(env, 'PATH') ?? '').split(':').filter(Boolean)
59
+ return dirs.some((dir) => {
60
+ const file = dir ? join(dir, name) : name
61
+ try {
62
+ accessSync(file, constants.X_OK)
63
+ return statSync(file).isFile()
64
+ } catch {
65
+ return false
66
+ }
67
+ })
68
+ }
69
+
70
+ // cmd.exe 认作有特殊含义的字符
71
+ const META = /([()\][%!^"`<>&|;, *?])/g
72
+
73
+ // 一个参数在 cmd.exe 的命令行里的写法:先按 Windows 程序解析参数的规则加引号、处理反斜杠与引号,
74
+ // 再给 cmd.exe 自己的特殊字符加 ^。经 node_modules/.bin 里的 .cmd 转一道的要转义两遍(它里面又解析一次)
75
+ function escapeArgument(value, twice) {
76
+ let arg = String(value)
77
+ arg = arg.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"')
78
+ arg = arg.replace(/(?=(\\+?)?)\1$/, '$1$1')
79
+ arg = `"${arg}"`.replace(META, '^$1')
80
+ return twice ? arg.replace(META, '^$1') : arg
81
+ }
82
+
83
+ // 怎么起这个命令:{ file, args, options, shell },交给 spawn、execFile;Windows 上找不到这个命令时为 null。
84
+ // shell 为真表示中间隔着一层 cmd.exe,结束它要用 killTree。别的系统上原样返回,找不到由系统报 ENOENT
85
+ export function launch(name, args, env, { platform = process.platform, exists } = {}) {
86
+ if (platform !== 'win32') return { file: name, args, options: {}, shell: false }
87
+ const file = findCommand(name, env, { exists })
88
+ if (!file) return null
89
+ if (!/\.(cmd|bat)$/i.test(file)) return { file, args, options: {}, shell: false }
90
+ // cmd.exe 把换行当成一行命令的结尾,后面的参数会悄悄丢掉:不起
91
+ if ([file, ...args].some((item) => /[\r\n]/.test(String(item)))) {
92
+ throw new KiokuFailure('参数里有换行,经 cmd.exe 起的命令收不到完整的参数')
93
+ }
94
+ const twice = /node_modules[\\/]\.bin[\\/][^\\/]+\.cmd$/i.test(file)
95
+ const line = [file.replace(META, '^$1'), ...args.map((arg) => escapeArgument(arg, twice))]
96
+ return {
97
+ file: envValue(env, 'ComSpec') || 'cmd.exe',
98
+ // /d 不跑注册表里的自动命令,/s 加外层引号让整行原样交给 /c
99
+ args: ['/d', '/s', '/c', `"${line.join(' ')}"`],
100
+ // 这一行已经按 cmd.exe 的规则写好了,不让 Node 再加一层引号
101
+ options: { windowsVerbatimArguments: true },
102
+ shell: true,
103
+ }
104
+ }
105
+
106
+ // 结束一个起好的命令。隔着 cmd.exe 时只结束它的话,真正的命令还活着、还占着输出的管道,
107
+ // 所以连它下面的进程一起结束(Windows 上没有信号可转,只能强行结束)
108
+ export function killTree(child, signal, { shell, platform = process.platform } = {}) {
109
+ if (platform !== 'win32' || !shell || child.pid === undefined) return child.kill(signal)
110
+ try {
111
+ spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' }).on(
112
+ 'error',
113
+ () => child.kill(),
114
+ )
115
+ return true
116
+ } catch {
117
+ return child.kill()
118
+ }
119
+ }
120
+
121
+ // 跑一个命令到结束,收下它的输出:{ found: false }(没有这个命令),
122
+ // 或者 { found: true, ok, stdout, output }(output 是两路输出合在一起,只用来认是哪种失败)。
123
+ // 超过时限就结束它(连同它下面的进程),算失败。不抛错
124
+ export function capture(name, args, env, { timeout, maxBuffer = 8 * 1024 * 1024 } = {}) {
125
+ let run
126
+ try {
127
+ run = launch(name, args, env)
128
+ } catch {
129
+ return Promise.resolve({ found: true, ok: false, stdout: '', output: '' })
130
+ }
131
+ if (!run) return Promise.resolve({ found: false })
132
+ return new Promise((resolve) => {
133
+ let timer
134
+ const child = execFile(
135
+ run.file,
136
+ run.args,
137
+ { env, maxBuffer, ...run.options },
138
+ (err, stdout, stderr) => {
139
+ clearTimeout(timer)
140
+ if (err?.code === 'ENOENT') resolve({ found: false })
141
+ else {
142
+ const out = String(stdout ?? '')
143
+ resolve({ found: true, ok: !err, stdout: out, output: `${out}\n${stderr ?? ''}` })
144
+ }
145
+ },
146
+ )
147
+ if (timeout) {
148
+ timer = setTimeout(() => killTree(child, 'SIGTERM', { shell: run.shell }), timeout)
149
+ timer.unref?.()
150
+ }
151
+ })
152
+ }
@@ -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
+ }