@kioku-memory/plugin-opencode 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.
@@ -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
+ }
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
+ }