@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.
- package/LICENSE +202 -0
- package/NOTICE +10 -0
- package/README.md +31 -2
- package/index.js +336 -0
- package/lib/agy.mjs +181 -0
- package/lib/api.mjs +38 -0
- package/lib/clean.mjs +96 -0
- package/lib/codex.mjs +320 -0
- package/lib/command.mjs +152 -0
- package/lib/config.mjs +50 -0
- package/lib/conflicts.mjs +1303 -0
- package/lib/connect.mjs +152 -0
- package/lib/doctor.mjs +158 -0
- package/lib/dsh.mjs +82 -0
- package/lib/files.mjs +92 -0
- package/lib/gemini.mjs +199 -0
- package/lib/hermes.mjs +276 -0
- package/lib/http.mjs +57 -0
- package/lib/import.mjs +301 -0
- package/lib/install.mjs +196 -0
- package/lib/kioku.mjs +451 -0
- package/lib/lifecycle.mjs +128 -0
- package/lib/local.mjs +294 -0
- package/lib/login.mjs +359 -0
- package/lib/mcp.mjs +142 -0
- package/lib/openclaw.mjs +256 -0
- package/lib/opencode.mjs +144 -0
- package/lib/panel.mjs +311 -0
- package/lib/pi.mjs +90 -0
- package/lib/platforms.mjs +297 -0
- package/lib/profile.mjs +100 -0
- package/lib/prompts.mjs +38 -0
- package/lib/redact.mjs +91 -0
- package/lib/secret.mjs +86 -0
- package/lib/setup.mjs +139 -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/lib/wizard.mjs +534 -0
- package/package.json +18 -4
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
// kioku setup 与 kioku doctor 认得的平台:自带的长期记忆在哪个配置文件里、怎么停用、怎么看现在的状态。
|
|
2
|
+
// 这里只描述配置,读写文件由 setup.mjs 做
|
|
3
|
+
|
|
4
|
+
import { readFile } from 'node:fs/promises'
|
|
5
|
+
import { homedir } from 'node:os'
|
|
6
|
+
import { join } from 'node:path'
|
|
7
|
+
|
|
8
|
+
import { agyHome, inspectAgy, preflightAgy, setupAgy, statusAgy } from './agy.mjs'
|
|
9
|
+
import { codexHome, inspectCodex, preflightCodex, setupCodex, statusCodex } from './codex.mjs'
|
|
10
|
+
import { dshHome, inspectDsh, setupDsh, statusDsh } from './dsh.mjs'
|
|
11
|
+
import { geminiHome, inspectGemini, preflightGemini, setupGemini, statusGemini } from './gemini.mjs'
|
|
12
|
+
import {
|
|
13
|
+
hermesHome,
|
|
14
|
+
inspectHermes,
|
|
15
|
+
preflightHermes,
|
|
16
|
+
readHermesConfig,
|
|
17
|
+
setupHermes,
|
|
18
|
+
statusHermes,
|
|
19
|
+
} from './hermes.mjs'
|
|
20
|
+
import { inspectOpenclaw, setupOpenclaw, statusOpenclaw } from './openclaw.mjs'
|
|
21
|
+
import {
|
|
22
|
+
inspectOpenCode,
|
|
23
|
+
opencodeHome,
|
|
24
|
+
preflightOpenCode,
|
|
25
|
+
setupOpenCode,
|
|
26
|
+
statusOpenCode,
|
|
27
|
+
} from './opencode.mjs'
|
|
28
|
+
import { inspectPi, piHome, setupPi, statusPi } from './pi.mjs'
|
|
29
|
+
import { readSettings } from './files.mjs'
|
|
30
|
+
import { readProfile } from './profile.mjs'
|
|
31
|
+
|
|
32
|
+
// 真值的环境变量写法
|
|
33
|
+
const TRUTHY = /^(1|true|yes|on)$/i
|
|
34
|
+
|
|
35
|
+
// 项目里优先于用户设置的两份设置文件
|
|
36
|
+
const PROJECT_SETTINGS = ['.claude/settings.local.json', '.claude/settings.json']
|
|
37
|
+
|
|
38
|
+
// 读一份 JSON 设置里的某一项;文件没有或读不懂时为 undefined
|
|
39
|
+
async function settingOf(file, key) {
|
|
40
|
+
try {
|
|
41
|
+
return JSON.parse((await readFile(file, 'utf8')).replace(/^\uFEFF/, ''))?.[key]
|
|
42
|
+
} catch {
|
|
43
|
+
return undefined
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function claudeHome(env) {
|
|
48
|
+
return env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude')
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// 向导的面板里各平台共有的几项:
|
|
52
|
+
// - command、home:本机装没装这个平台,看命令在不在 PATH 里、配置目录在不在
|
|
53
|
+
// - status:插件装没装(plugin:true、false,null 是查不了)与自带的长期记忆停没停(memory:'off'、'on',
|
|
54
|
+
// 'none' 是没有自带的,null 是查不了);reenabledIn 是又启用了它、停用不了的那份设置
|
|
55
|
+
// - install:插件要用户自己装:在哪里运行(where,默认终端)、可以直接复制的命令与之后要做的事;向导不替用户装
|
|
56
|
+
// - source:kioku import 认得的本地记忆的来源
|
|
57
|
+
const claudeCode = {
|
|
58
|
+
name: 'Claude Code',
|
|
59
|
+
command: () => 'claude',
|
|
60
|
+
home: claudeHome,
|
|
61
|
+
// 项目的设置又启用了自动记忆时,停用用户设置也没用:reenabledIn 写明是哪份文件,向导据此不再提供停用
|
|
62
|
+
status: async ({ env, cwd }) => {
|
|
63
|
+
let settings
|
|
64
|
+
try {
|
|
65
|
+
;({ settings } = await readSettings(claudeCode.settingsFile(env)))
|
|
66
|
+
} catch {
|
|
67
|
+
return { plugin: null, memory: null }
|
|
68
|
+
}
|
|
69
|
+
const plugin = claudeCode.pluginActive(settings, env)
|
|
70
|
+
const reenabledIn = await claudeCode.memory.enabledIn(env, cwd)
|
|
71
|
+
if (reenabledIn) return { plugin, memory: 'on', reenabledIn }
|
|
72
|
+
return { plugin, memory: claudeCode.memory.disabledBy(settings, env) ? 'off' : 'on' }
|
|
73
|
+
},
|
|
74
|
+
install: {
|
|
75
|
+
where: '在 Claude Code 里',
|
|
76
|
+
commands: ['/plugin install kioku --marketplace lonelyman0108/kioku-plugins'],
|
|
77
|
+
after: '启用时填 Kioku 的地址与访问密钥(管理界面的应用页签发),新开会话生效',
|
|
78
|
+
},
|
|
79
|
+
source: 'claude-code',
|
|
80
|
+
// 应用的运行时要是这个,服务端才按这个平台给注入
|
|
81
|
+
runtimeFamily: 'claudecode',
|
|
82
|
+
// 这个平台的会话里有的环境变量,不写平台时靠它认出来
|
|
83
|
+
detect: (env) => env.CLAUDECODE === '1',
|
|
84
|
+
// 用户级的设置文件
|
|
85
|
+
settingsFile: (env) => join(claudeHome(env), 'settings.json'),
|
|
86
|
+
memory: {
|
|
87
|
+
name: '自动记忆(auto memory)',
|
|
88
|
+
// 停用:用户设置里把 autoMemoryEnabled 设为 false
|
|
89
|
+
disable: (settings) => ({ ...settings, autoMemoryEnabled: false }),
|
|
90
|
+
// 还原:去掉这一项,回到默认(开着)
|
|
91
|
+
restore: (settings) => {
|
|
92
|
+
const rest = { ...settings }
|
|
93
|
+
delete rest.autoMemoryEnabled
|
|
94
|
+
return rest
|
|
95
|
+
},
|
|
96
|
+
changed: ['autoMemoryEnabled'],
|
|
97
|
+
// 现在是不是停用的,以及是哪里停用的
|
|
98
|
+
disabledBy: (settings, env) => {
|
|
99
|
+
if (TRUTHY.test((env.CLAUDE_CODE_DISABLE_AUTO_MEMORY ?? '').trim())) {
|
|
100
|
+
return '环境变量 CLAUDE_CODE_DISABLE_AUTO_MEMORY'
|
|
101
|
+
}
|
|
102
|
+
return settings?.autoMemoryEnabled === false ? '用户设置' : null
|
|
103
|
+
},
|
|
104
|
+
// 又在哪份项目设置里启用了(相对项目目录的路径):当前项目的设置优先于用户设置。别处(托管的设置)查不到
|
|
105
|
+
enabledIn: async (env, cwd) => {
|
|
106
|
+
// 环境变量停用着时,设置里写什么都不生效
|
|
107
|
+
if (TRUTHY.test((env.CLAUDE_CODE_DISABLE_AUTO_MEMORY ?? '').trim())) return null
|
|
108
|
+
for (const name of PROJECT_SETTINGS) {
|
|
109
|
+
if ((await settingOf(join(cwd, name), 'autoMemoryEnabled')) === true) return name
|
|
110
|
+
}
|
|
111
|
+
return null
|
|
112
|
+
},
|
|
113
|
+
// 同上,给提示用的说法
|
|
114
|
+
enabledBy: async (env, cwd) => {
|
|
115
|
+
const name = await claudeCode.memory.enabledIn(env, cwd)
|
|
116
|
+
return name ? `项目的 ${name} ` : null
|
|
117
|
+
},
|
|
118
|
+
},
|
|
119
|
+
// 插件是否在用:这个会话里钩子已经配好了访问密钥文件,或者用户设置的 enabledPlugins 里有以「kioku@」开头、
|
|
120
|
+
// 值为 true 的一项。项目级的设置里启用的认不出来,所以认不出时只提醒、不算有问题
|
|
121
|
+
pluginActive: (settings, env) =>
|
|
122
|
+
Boolean(env.KIOKU_API_KEY_FILE) ||
|
|
123
|
+
Object.entries(settings?.enabledPlugins ?? {}).some(
|
|
124
|
+
([id, on]) => id.startsWith('kioku@') && on === true,
|
|
125
|
+
),
|
|
126
|
+
pluginHint: '在 Claude Code 里用 /plugin 安装并启用 kioku',
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const codex = {
|
|
130
|
+
name: 'Codex',
|
|
131
|
+
runtimeFamily: 'codex',
|
|
132
|
+
command: () => 'codex',
|
|
133
|
+
home: codexHome,
|
|
134
|
+
status: statusCodex,
|
|
135
|
+
install: {
|
|
136
|
+
commands: [
|
|
137
|
+
'codex plugin marketplace add lonelyman0108/kioku-plugins',
|
|
138
|
+
'codex plugin add kioku@kioku',
|
|
139
|
+
],
|
|
140
|
+
after: '打开 codex,在 /hooks 里信任 kioku 的三个钩子,新开会话生效',
|
|
141
|
+
},
|
|
142
|
+
// Codex 的会话里没有可靠的标记,要写明平台
|
|
143
|
+
detect: () => false,
|
|
144
|
+
// 地址与访问密钥放在本机的文件里(profile.mjs);readConfig 读出来给 doctor、login、import 用
|
|
145
|
+
readConfig: (env) => readProfile('codex', env),
|
|
146
|
+
setup: setupCodex,
|
|
147
|
+
// kioku login 申请之前先做的检查
|
|
148
|
+
preflight: preflightCodex,
|
|
149
|
+
inspect: inspectCodex,
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const pi = {
|
|
153
|
+
name: 'pi',
|
|
154
|
+
runtimeFamily: 'pi',
|
|
155
|
+
command: () => 'pi',
|
|
156
|
+
home: piHome,
|
|
157
|
+
status: statusPi,
|
|
158
|
+
install: {
|
|
159
|
+
commands: ['pi install git:github.com/lonelyman0108/kioku-plugins'],
|
|
160
|
+
after: '新开 pi 会话(或 /reload)生效',
|
|
161
|
+
},
|
|
162
|
+
detect: () => false,
|
|
163
|
+
readConfig: (env) => readProfile('pi', env),
|
|
164
|
+
setup: setupPi,
|
|
165
|
+
inspect: inspectPi,
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const hermes = {
|
|
169
|
+
name: 'Hermes',
|
|
170
|
+
runtimeFamily: 'hermes',
|
|
171
|
+
command: (env) => env.KIOKU_HERMES_BIN || 'hermes',
|
|
172
|
+
home: hermesHome,
|
|
173
|
+
status: statusHermes,
|
|
174
|
+
install: {
|
|
175
|
+
commands: ['hermes plugins install lonelyman0108/kioku-plugins/plugins/hermes --enable'],
|
|
176
|
+
after: '新开 Hermes 会话生效',
|
|
177
|
+
},
|
|
178
|
+
source: 'hermes',
|
|
179
|
+
detect: () => false,
|
|
180
|
+
// 地址与访问密钥在 Hermes 自己的 .env 里
|
|
181
|
+
readConfig: readHermesConfig,
|
|
182
|
+
setup: setupHermes,
|
|
183
|
+
preflight: preflightHermes,
|
|
184
|
+
inspect: inspectHermes,
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
const openclaw = {
|
|
188
|
+
name: 'OpenClaw',
|
|
189
|
+
runtimeFamily: 'openclaw',
|
|
190
|
+
command: (env) => env.KIOKU_OPENCLAW_BIN || 'openclaw',
|
|
191
|
+
home: (env) => join(env.OPENCLAW_HOME || homedir(), '.openclaw'),
|
|
192
|
+
status: statusOpenclaw,
|
|
193
|
+
install: {
|
|
194
|
+
commands: ['openclaw plugins install npm:@kioku-memory/openclaw', 'openclaw gateway restart'],
|
|
195
|
+
after: '重启网关之后生效',
|
|
196
|
+
},
|
|
197
|
+
source: 'openclaw',
|
|
198
|
+
detect: () => false,
|
|
199
|
+
readConfig: (env) => readProfile('openclaw', env),
|
|
200
|
+
setup: setupOpenclaw,
|
|
201
|
+
inspect: inspectOpenclaw,
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const dsh = {
|
|
205
|
+
name: 'DeepSeek Harness',
|
|
206
|
+
runtimeFamily: 'dsh',
|
|
207
|
+
command: () => 'dsh',
|
|
208
|
+
home: dshHome,
|
|
209
|
+
status: statusDsh,
|
|
210
|
+
install: {
|
|
211
|
+
commands: ['dsh plugin --profile <profile> add github:lonelyman0108/kioku-plugins'],
|
|
212
|
+
after: '<profile> 换成要用的 profile(web、tui 这些各装一次),重启 dsh 生效',
|
|
213
|
+
},
|
|
214
|
+
detect: () => false,
|
|
215
|
+
readConfig: (env) => readProfile('dsh', env),
|
|
216
|
+
setup: setupDsh,
|
|
217
|
+
inspect: inspectDsh,
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const opencode = {
|
|
221
|
+
name: 'OpenCode',
|
|
222
|
+
runtimeFamily: 'opencode',
|
|
223
|
+
command: () => 'opencode',
|
|
224
|
+
home: opencodeHome,
|
|
225
|
+
status: statusOpenCode,
|
|
226
|
+
install: {
|
|
227
|
+
commands: ['opencode'],
|
|
228
|
+
after:
|
|
229
|
+
'确认 opencode.json 的 plugin 已包含 @kioku-memory/plugin-opencode(kioku setup opencode 会写入),新开会话生效',
|
|
230
|
+
},
|
|
231
|
+
detect: (env) => Boolean(env.OPENCODE),
|
|
232
|
+
readConfig: (env) => readProfile('opencode', env),
|
|
233
|
+
preflight: preflightOpenCode,
|
|
234
|
+
setup: setupOpenCode,
|
|
235
|
+
inspect: inspectOpenCode,
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const gemini = {
|
|
239
|
+
name: 'Gemini CLI',
|
|
240
|
+
runtimeFamily: 'gemini',
|
|
241
|
+
command: () => 'gemini',
|
|
242
|
+
home: geminiHome,
|
|
243
|
+
status: statusGemini,
|
|
244
|
+
install: {
|
|
245
|
+
commands: [
|
|
246
|
+
'git clone https://github.com/lonelyman0108/kioku-plugins',
|
|
247
|
+
'gemini extensions link kioku-plugins/plugins/gemini',
|
|
248
|
+
],
|
|
249
|
+
after: '重启 Gemini CLI 生效(MCP 与停用 save_memory 已由 kioku setup gemini 配好)',
|
|
250
|
+
},
|
|
251
|
+
detect: (env) => Boolean(env.GEMINI_CLI),
|
|
252
|
+
readConfig: (env) => readProfile('gemini', env),
|
|
253
|
+
preflight: preflightGemini,
|
|
254
|
+
setup: setupGemini,
|
|
255
|
+
inspect: inspectGemini,
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const agy = {
|
|
259
|
+
name: 'Antigravity',
|
|
260
|
+
runtimeFamily: 'agy',
|
|
261
|
+
command: () => 'agy',
|
|
262
|
+
home: agyHome,
|
|
263
|
+
status: statusAgy,
|
|
264
|
+
install: {
|
|
265
|
+
commands: [
|
|
266
|
+
'git clone https://github.com/lonelyman0108/kioku-plugins',
|
|
267
|
+
'mkdir -p ~/.gemini/config/plugins && cp -r kioku-plugins/plugins/agy ~/.gemini/config/plugins/kioku',
|
|
268
|
+
],
|
|
269
|
+
after: '新开会话生效(MCP 服务已由 kioku setup agy 写进 mcp_config.json)',
|
|
270
|
+
},
|
|
271
|
+
detect: (env) => Boolean(env.ANTIGRAVITY_AGENT || env.AGY_SESSION_ID),
|
|
272
|
+
readConfig: (env) => readProfile('agy', env),
|
|
273
|
+
preflight: preflightAgy,
|
|
274
|
+
setup: setupAgy,
|
|
275
|
+
inspect: inspectAgy,
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
export const PLATFORMS = {
|
|
279
|
+
'claude-code': claudeCode,
|
|
280
|
+
codex,
|
|
281
|
+
pi,
|
|
282
|
+
hermes,
|
|
283
|
+
openclaw,
|
|
284
|
+
dsh,
|
|
285
|
+
opencode,
|
|
286
|
+
gemini,
|
|
287
|
+
agy,
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
export function platformNames() {
|
|
291
|
+
return Object.keys(PLATFORMS).join('、')
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// 不写平台时按环境变量认;认不出为 null
|
|
295
|
+
export function detectPlatform(env) {
|
|
296
|
+
return Object.keys(PLATFORMS).find((id) => PLATFORMS[id].detect(env)) ?? null
|
|
297
|
+
}
|
package/lib/profile.mjs
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
// 没有自己的密钥存储的平台(Codex、pi 这类),地址与访问密钥放在本机的一个文件里:
|
|
2
|
+
// <配置目录>/kioku/<平台>.json,只给本人读写。kioku setup 写它,各平台的钩子与 kioku doctor 读它。
|
|
3
|
+
// 一个平台一个文件:每个平台在 Kioku 里是各自的应用,访问密钥不共用
|
|
4
|
+
|
|
5
|
+
import { randomUUID } from 'node:crypto'
|
|
6
|
+
import { chmod, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
|
|
7
|
+
import { homedir } from 'node:os'
|
|
8
|
+
import { join } from 'node:path'
|
|
9
|
+
|
|
10
|
+
import { errorKind, keyFormatError, KiokuFailure } from './http.mjs'
|
|
11
|
+
|
|
12
|
+
// 平台名要拼进文件名,只收这些字符
|
|
13
|
+
const PLATFORM = /^[a-z][a-z0-9-]{0,31}$/
|
|
14
|
+
|
|
15
|
+
// 放这些文件的目录:KIOKU_CONFIG_DIR,否则 XDG 的配置目录下的 kioku
|
|
16
|
+
export function profileDir(env) {
|
|
17
|
+
if (env.KIOKU_CONFIG_DIR) return env.KIOKU_CONFIG_DIR
|
|
18
|
+
return join(env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'kioku')
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function profileFile(platform, env) {
|
|
22
|
+
if (!PLATFORM.test(platform)) throw new KiokuFailure('平台名不对')
|
|
23
|
+
return join(profileDir(env), `${platform}.json`)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// 服务地址:去掉首尾空白与结尾的斜杠;不是 http(s) 地址、或者带着账号密码、查询参数时返回原因
|
|
27
|
+
export function serverUrlProblem(url) {
|
|
28
|
+
// URL 解析会悄悄去掉中间的换行与制表符:原样写进配置文件的是带着它们的那一份
|
|
29
|
+
if (/[\s\p{Cc}]/u.test(url)) return '服务地址里不能有空白或控制字符'
|
|
30
|
+
let parsed
|
|
31
|
+
try {
|
|
32
|
+
parsed = new URL(url)
|
|
33
|
+
} catch {
|
|
34
|
+
return '服务地址不是有效的地址'
|
|
35
|
+
}
|
|
36
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
|
37
|
+
return '服务地址要以 http:// 或 https:// 开头'
|
|
38
|
+
}
|
|
39
|
+
if (parsed.username || parsed.password || parsed.search || parsed.hash) {
|
|
40
|
+
return '服务地址里不要带账号密码、查询参数'
|
|
41
|
+
}
|
|
42
|
+
return null
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// 读这个平台的地址与访问密钥。没有这个文件时为 null;文件读不懂、内容不对时抛 KiokuFailure,
|
|
46
|
+
// 文字只写文件的位置与问题,不带内容
|
|
47
|
+
export async function readProfile(platform, env) {
|
|
48
|
+
const file = profileFile(platform, env)
|
|
49
|
+
let text
|
|
50
|
+
try {
|
|
51
|
+
text = await readFile(file, 'utf8')
|
|
52
|
+
} catch (err) {
|
|
53
|
+
if (err?.code === 'ENOENT') return null
|
|
54
|
+
throw new KiokuFailure(`无法读取 ${file}(${errorKind(err)})`)
|
|
55
|
+
}
|
|
56
|
+
let data
|
|
57
|
+
try {
|
|
58
|
+
data = JSON.parse(text)
|
|
59
|
+
} catch {
|
|
60
|
+
data = null
|
|
61
|
+
}
|
|
62
|
+
const url = typeof data?.serverUrl === 'string' ? data.serverUrl.trim().replace(/\/+$/, '') : ''
|
|
63
|
+
const key = typeof data?.apiKey === 'string' ? data.apiKey.trim() : ''
|
|
64
|
+
if (!url || !key) throw new KiokuFailure(`${file} 里没有服务地址或访问密钥`)
|
|
65
|
+
const problem = serverUrlProblem(url) ?? keyFormatError(key)
|
|
66
|
+
if (problem) throw new KiokuFailure(`${file}:${problem}`)
|
|
67
|
+
return { url, key, file }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// 写这个平台的地址与访问密钥:目录与文件都只给本人,先写临时文件再改名
|
|
71
|
+
export async function writeProfile(platform, { url, key }, env) {
|
|
72
|
+
const file = profileFile(platform, env)
|
|
73
|
+
const clean = url.trim().replace(/\/+$/, '')
|
|
74
|
+
const problem = serverUrlProblem(clean) ?? keyFormatError(key)
|
|
75
|
+
if (problem) throw new KiokuFailure(problem)
|
|
76
|
+
const temp = `${file}.${randomUUID()}.tmp`
|
|
77
|
+
try {
|
|
78
|
+
await mkdir(profileDir(env), { recursive: true, mode: 0o700 })
|
|
79
|
+
const body = `${JSON.stringify({ serverUrl: clean, apiKey: key }, null, 2)}\n`
|
|
80
|
+
await writeFile(temp, body, { mode: 0o600, flag: 'wx' })
|
|
81
|
+
// 已有的文件权限可能更宽,改名之后以新文件的为准;再收一次,不受 umask 影响
|
|
82
|
+
await chmod(temp, 0o600)
|
|
83
|
+
await rename(temp, file)
|
|
84
|
+
} catch (err) {
|
|
85
|
+
await rm(temp, { force: true }).catch(() => {})
|
|
86
|
+
throw new KiokuFailure(`无法写入 ${file}(${errorKind(err)})`)
|
|
87
|
+
}
|
|
88
|
+
return file
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export async function removeProfile(platform, env) {
|
|
92
|
+
const file = profileFile(platform, env)
|
|
93
|
+
try {
|
|
94
|
+
await rm(file)
|
|
95
|
+
return file
|
|
96
|
+
} catch (err) {
|
|
97
|
+
if (err?.code === 'ENOENT') return null
|
|
98
|
+
throw new KiokuFailure(`无法删除 ${file}(${errorKind(err)})`)
|
|
99
|
+
}
|
|
100
|
+
}
|
package/lib/prompts.mjs
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// 向导的交互层:@clack/prompts。它只是 npm 上的 @kioku-memory/cli 的依赖:插件目录里的那几份 kioku
|
|
2
|
+
// 是复制进去的,带不了依赖,所以这里按需装载,装不到时返回 null,由调用方说明怎么装。别的子命令不经过这里
|
|
3
|
+
|
|
4
|
+
// @clack/prompts 要求的 Node 版本
|
|
5
|
+
const MIN_NODE = [20, 12]
|
|
6
|
+
|
|
7
|
+
export function nodeSupported(version = process.versions.node) {
|
|
8
|
+
const [major, minor] = version.split('.').map(Number)
|
|
9
|
+
return major > MIN_NODE[0] || (major === MIN_NODE[0] && minor >= MIN_NODE[1])
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
// 交互库自带的英文换成中文:操作说明不显示(多选的写进问题里),是与否、取消与出错的文字改掉
|
|
13
|
+
export function localized(clack) {
|
|
14
|
+
clack.updateSettings?.({ messages: { cancel: '已取消', error: '出错了' } })
|
|
15
|
+
return {
|
|
16
|
+
...clack,
|
|
17
|
+
select: (options) => clack.select({ showInstructions: false, ...options }),
|
|
18
|
+
multiselect: (options) =>
|
|
19
|
+
clack.multiselect({
|
|
20
|
+
showInstructions: false,
|
|
21
|
+
required: false,
|
|
22
|
+
...options,
|
|
23
|
+
message: `${options.message}(空格选中,回车确认)`,
|
|
24
|
+
}),
|
|
25
|
+
confirm: (options) => clack.confirm({ active: '是', inactive: '否', ...options }),
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export async function loadPrompts() {
|
|
30
|
+
if (!nodeSupported()) return null
|
|
31
|
+
let clack
|
|
32
|
+
try {
|
|
33
|
+
clack = await import('@clack/prompts')
|
|
34
|
+
} catch {
|
|
35
|
+
return null
|
|
36
|
+
}
|
|
37
|
+
return localized(clack)
|
|
38
|
+
}
|
package/lib/redact.mjs
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// 打码:输出里原样出现的值换成 ***。按字节比对、不解码,所以不会把一个字符拆开,
|
|
2
|
+
// 不是 UTF-8 的输出(例如二进制)也原样通过。只防值顺手出现在输出里,不是安全边界:
|
|
3
|
+
// 值被编码、拆开或改了大小写后再打印,就认不出来
|
|
4
|
+
|
|
5
|
+
import { PassThrough, Transform } from 'node:stream'
|
|
6
|
+
|
|
7
|
+
const MASK = Buffer.from('***')
|
|
8
|
+
|
|
9
|
+
// 少于这么多个字符的值不打码:这么短的串在输出里到处都是,换掉会误伤
|
|
10
|
+
export const MIN_REDACT_CHARS = 4
|
|
11
|
+
|
|
12
|
+
export function redactable(value) {
|
|
13
|
+
return [...value].length >= MIN_REDACT_CHARS
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// buf 的结尾是某个值的开头(一次还没写完的出现)时,返回这一段的长度,否则为 0
|
|
17
|
+
function partialTail(buf, needles) {
|
|
18
|
+
let longest = 0
|
|
19
|
+
for (const needle of needles) {
|
|
20
|
+
// 从最长的可能找起,第一个对上的就是这个值能留下的最长一段
|
|
21
|
+
for (let at = Math.max(0, buf.length - needle.length + 1); at < buf.length; at++) {
|
|
22
|
+
const length = buf.length - at
|
|
23
|
+
if (length <= longest) break
|
|
24
|
+
if (buf[at] === needle[0] && buf.subarray(at).equals(needle.subarray(0, length))) {
|
|
25
|
+
longest = length
|
|
26
|
+
break
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return longest
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// 返回一个 Transform:写进去原始输出,读出来打过码的输出。
|
|
34
|
+
// 值可能被拆在相邻的两块里:块的结尾像某个值的开头时,这一段先留着,拼上下一块再判断,结束时冲刷出去。
|
|
35
|
+
// 几个值互相包含或重叠时,盖住的范围取并集,连成一片的只写一个 ***
|
|
36
|
+
export function createRedactor(values) {
|
|
37
|
+
const needles = [...new Set(values.filter(redactable))].map((v) => Buffer.from(v, 'utf8'))
|
|
38
|
+
if (needles.length === 0) return new PassThrough()
|
|
39
|
+
let pending = Buffer.alloc(0)
|
|
40
|
+
// pending 开头已经确定盖住的字节数:上一次写出的最后一段延续到了这里
|
|
41
|
+
let carry = 0
|
|
42
|
+
// 上一次写出的最后一个字节盖住了没有:盖住的话,从 pending 开头接着盖的部分不再另写 ***
|
|
43
|
+
let covered = false
|
|
44
|
+
|
|
45
|
+
function drain(final) {
|
|
46
|
+
const limit = final ? pending.length : pending.length - partialTail(pending, needles)
|
|
47
|
+
if (limit <= 0) return null
|
|
48
|
+
// [0, limit) 里每个字节盖不盖住都已经定了:盖住它的出现都从 limit 之前开始,而且都完整地在 pending 里
|
|
49
|
+
const ranges = carry > 0 ? [[0, carry]] : []
|
|
50
|
+
for (const needle of needles) {
|
|
51
|
+
for (
|
|
52
|
+
let at = pending.indexOf(needle);
|
|
53
|
+
at !== -1 && at < limit;
|
|
54
|
+
at = pending.indexOf(needle, at + 1)
|
|
55
|
+
) {
|
|
56
|
+
ranges.push([at, at + needle.length])
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
ranges.sort((a, b) => a[0] - b[0])
|
|
60
|
+
const runs = []
|
|
61
|
+
for (const [from, to] of ranges) {
|
|
62
|
+
const last = runs.at(-1)
|
|
63
|
+
if (last && from <= last[1]) last[1] = Math.max(last[1], to)
|
|
64
|
+
else runs.push([from, to])
|
|
65
|
+
}
|
|
66
|
+
const parts = []
|
|
67
|
+
let pos = 0
|
|
68
|
+
for (const [from, to] of runs) {
|
|
69
|
+
if (from > pos) parts.push(pending.subarray(pos, from))
|
|
70
|
+
if (from > 0 || !covered) parts.push(MASK)
|
|
71
|
+
pos = Math.min(to, limit)
|
|
72
|
+
}
|
|
73
|
+
if (pos < limit) parts.push(pending.subarray(pos, limit))
|
|
74
|
+
const reach = runs.length > 0 ? runs.at(-1)[1] : 0
|
|
75
|
+
covered = reach >= limit
|
|
76
|
+
carry = Math.max(0, reach - limit)
|
|
77
|
+
pending = pending.subarray(limit)
|
|
78
|
+
return Buffer.concat(parts)
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const emit = (callback, out) => callback(null, out?.length ? out : undefined)
|
|
82
|
+
return new Transform({
|
|
83
|
+
transform(chunk, _encoding, callback) {
|
|
84
|
+
pending = pending.length > 0 ? Buffer.concat([pending, chunk]) : chunk
|
|
85
|
+
emit(callback, drain(false))
|
|
86
|
+
},
|
|
87
|
+
flush(callback) {
|
|
88
|
+
emit(callback, drain(true))
|
|
89
|
+
},
|
|
90
|
+
})
|
|
91
|
+
}
|
package/lib/secret.mjs
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// 读访问密钥,不经过命令行参数(会进 shell 的历史与进程列表):先看 KIOKU_API_KEY,
|
|
2
|
+
// 标准输入不是终端时读它的全部内容,是终端时提示输入、不回显
|
|
3
|
+
|
|
4
|
+
import { StringDecoder } from 'node:string_decoder'
|
|
5
|
+
|
|
6
|
+
import { KiokuFailure } from './http.mjs'
|
|
7
|
+
|
|
8
|
+
async function readAll(stream) {
|
|
9
|
+
const chunks = []
|
|
10
|
+
for await (const chunk of stream) chunks.push(chunk)
|
|
11
|
+
return Buffer.concat(chunks).toString('utf8')
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// 终端发来的转义序列(方向键、粘贴的起止标记这类):不是输入的内容
|
|
15
|
+
// eslint-disable-next-line no-control-regex
|
|
16
|
+
const ESCAPES = /\u001b(?:\[[0-9;?]*[ -/]*[@-~]|O.|.)?/g
|
|
17
|
+
|
|
18
|
+
// 把终端发来的一段字符并进已经输入的内容,返回 { value, done }:done 为 'enter' 是输完了,'cancel' 是取消。
|
|
19
|
+
// 回车结束,Ctrl-C、Ctrl-D 取消,退格删掉一个字,Ctrl-U 清空;别的控制字符与转义序列不算输入
|
|
20
|
+
export function applyKeys(value, text) {
|
|
21
|
+
let chars = Array.from(value)
|
|
22
|
+
for (const char of text.replace(ESCAPES, '')) {
|
|
23
|
+
if (char === '\r' || char === '\n') return { value: chars.join(''), done: 'enter' }
|
|
24
|
+
if (char === '\u0003' || char === '\u0004') return { value: '', done: 'cancel' }
|
|
25
|
+
if (char === '\u007f' || char === '\b') chars.pop()
|
|
26
|
+
else if (char === '\u0015') chars = []
|
|
27
|
+
else if (!/\p{Cc}/u.test(char)) chars.push(char)
|
|
28
|
+
}
|
|
29
|
+
return { value: chars.join(''), done: null }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// 在终端里读一行,不回显。不管怎么结束都把终端改回原来的模式
|
|
33
|
+
function readHidden(stdin, out, label) {
|
|
34
|
+
return new Promise((resolve, reject) => {
|
|
35
|
+
let value = ''
|
|
36
|
+
// 一个字可能被切在两块里:按 UTF-8 接着解码
|
|
37
|
+
const decoder = new StringDecoder('utf8')
|
|
38
|
+
const finish = (fn, arg) => {
|
|
39
|
+
stdin.off('data', onData)
|
|
40
|
+
stdin.off('end', onEnd)
|
|
41
|
+
stdin.off('error', onError)
|
|
42
|
+
try {
|
|
43
|
+
stdin.setRawMode(false)
|
|
44
|
+
} catch {
|
|
45
|
+
// 终端已经没了
|
|
46
|
+
}
|
|
47
|
+
stdin.pause()
|
|
48
|
+
out.write('\n')
|
|
49
|
+
fn(arg)
|
|
50
|
+
}
|
|
51
|
+
const onData = (chunk) => {
|
|
52
|
+
const result = applyKeys(value, decoder.write(chunk))
|
|
53
|
+
value = result.value
|
|
54
|
+
if (result.done === 'enter') finish(resolve, value)
|
|
55
|
+
else if (result.done === 'cancel') finish(reject, new KiokuFailure('已取消'))
|
|
56
|
+
}
|
|
57
|
+
// 终端挂断:按取消算,不拿半截的输入当访问密钥
|
|
58
|
+
const onEnd = () => finish(reject, new KiokuFailure('输入中断了,没有读到访问密钥'))
|
|
59
|
+
const onError = () => finish(reject, new KiokuFailure('无法从终端读取访问密钥'))
|
|
60
|
+
out.write(label)
|
|
61
|
+
stdin.setRawMode(true)
|
|
62
|
+
stdin.resume()
|
|
63
|
+
stdin.on('data', onData)
|
|
64
|
+
stdin.on('end', onEnd)
|
|
65
|
+
stdin.on('error', onError)
|
|
66
|
+
})
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// 没有给访问密钥时返回空字符串
|
|
70
|
+
export async function readSecret({
|
|
71
|
+
env = process.env,
|
|
72
|
+
stdin = process.stdin,
|
|
73
|
+
out = process.stderr,
|
|
74
|
+
canLogin = false,
|
|
75
|
+
hasSaved = false,
|
|
76
|
+
} = {}) {
|
|
77
|
+
const fromEnv = (env.KIOKU_API_KEY ?? '').trim()
|
|
78
|
+
if (fromEnv) return fromEnv
|
|
79
|
+
if (!stdin.isTTY) return (await readAll(stdin)).trim()
|
|
80
|
+
const label = hasSaved
|
|
81
|
+
? '访问密钥(不回显;直接回车沿用上次的):'
|
|
82
|
+
: canLogin
|
|
83
|
+
? '访问密钥(不回显;直接回车改用浏览器授权):'
|
|
84
|
+
: '访问密钥(不回显):'
|
|
85
|
+
return (await readHidden(stdin, out, label)).trim()
|
|
86
|
+
}
|