@kioku-memory/cli 0.0.0 → 0.2.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/NOTICE +3 -0
- package/README.md +129 -4
- package/bin/kioku +11 -0
- package/lib/api.mjs +38 -0
- package/lib/codex.mjs +320 -0
- package/lib/command.mjs +152 -0
- package/lib/config.mjs +6 -4
- package/lib/connect.mjs +152 -0
- package/lib/doctor.mjs +32 -50
- package/lib/dsh.mjs +82 -0
- package/lib/files.mjs +92 -0
- package/lib/hermes.mjs +276 -0
- package/lib/import.mjs +301 -0
- package/lib/install.mjs +146 -0
- package/lib/kioku.mjs +59 -8
- package/lib/lifecycle.mjs +29 -4
- package/lib/local.mjs +294 -0
- package/lib/login.mjs +347 -0
- package/lib/mcp.mjs +142 -0
- package/lib/openclaw.mjs +256 -0
- package/lib/panel.mjs +295 -0
- package/lib/pi.mjs +90 -0
- package/lib/platforms.mjs +147 -6
- package/lib/profile.mjs +100 -0
- package/lib/prompts.mjs +38 -0
- package/lib/secret.mjs +86 -0
- package/lib/setup.mjs +50 -92
- package/lib/sources.mjs +333 -0
- package/lib/target.mjs +62 -0
- package/lib/text.mjs +14 -0
- package/lib/wizard.mjs +447 -0
- package/package.json +5 -2
package/lib/platforms.mjs
CHANGED
|
@@ -5,6 +5,21 @@ import { readFile } from 'node:fs/promises'
|
|
|
5
5
|
import { homedir } from 'node:os'
|
|
6
6
|
import { join } from 'node:path'
|
|
7
7
|
|
|
8
|
+
import { codexHome, inspectCodex, preflightCodex, setupCodex, statusCodex } from './codex.mjs'
|
|
9
|
+
import { dshHome, inspectDsh, setupDsh, statusDsh } from './dsh.mjs'
|
|
10
|
+
import {
|
|
11
|
+
hermesHome,
|
|
12
|
+
inspectHermes,
|
|
13
|
+
preflightHermes,
|
|
14
|
+
readHermesConfig,
|
|
15
|
+
setupHermes,
|
|
16
|
+
statusHermes,
|
|
17
|
+
} from './hermes.mjs'
|
|
18
|
+
import { inspectOpenclaw, setupOpenclaw, statusOpenclaw } from './openclaw.mjs'
|
|
19
|
+
import { inspectPi, piHome, setupPi, statusPi } from './pi.mjs'
|
|
20
|
+
import { readSettings } from './files.mjs'
|
|
21
|
+
import { readProfile } from './profile.mjs'
|
|
22
|
+
|
|
8
23
|
// 真值的环境变量写法
|
|
9
24
|
const TRUTHY = /^(1|true|yes|on)$/i
|
|
10
25
|
|
|
@@ -20,14 +35,45 @@ async function settingOf(file, key) {
|
|
|
20
35
|
}
|
|
21
36
|
}
|
|
22
37
|
|
|
38
|
+
function claudeHome(env) {
|
|
39
|
+
return env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude')
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// 向导的面板里各平台共有的几项:
|
|
43
|
+
// - command、home:本机装没装这个平台,看命令在不在 PATH 里、配置目录在不在
|
|
44
|
+
// - status:插件装没装(plugin:true、false,null 是查不了)与自带的长期记忆停没停(memory:'off'、'on',
|
|
45
|
+
// 'none' 是没有自带的,null 是查不了);reenabledIn 是又启用了它、停用不了的那份设置
|
|
46
|
+
// - install:插件要用户自己装:在哪里运行(where,默认终端)、可以直接复制的命令与之后要做的事;向导不替用户装
|
|
47
|
+
// - source:kioku import 认得的本地记忆的来源
|
|
23
48
|
const claudeCode = {
|
|
24
49
|
name: 'Claude Code',
|
|
50
|
+
command: () => 'claude',
|
|
51
|
+
home: claudeHome,
|
|
52
|
+
// 项目的设置又启用了自动记忆时,停用用户设置也没用:reenabledIn 写明是哪份文件,向导据此不再提供停用
|
|
53
|
+
status: async ({ env, cwd }) => {
|
|
54
|
+
let settings
|
|
55
|
+
try {
|
|
56
|
+
;({ settings } = await readSettings(claudeCode.settingsFile(env)))
|
|
57
|
+
} catch {
|
|
58
|
+
return { plugin: null, memory: null }
|
|
59
|
+
}
|
|
60
|
+
const plugin = claudeCode.pluginActive(settings, env)
|
|
61
|
+
const reenabledIn = await claudeCode.memory.enabledIn(env, cwd)
|
|
62
|
+
if (reenabledIn) return { plugin, memory: 'on', reenabledIn }
|
|
63
|
+
return { plugin, memory: claudeCode.memory.disabledBy(settings, env) ? 'off' : 'on' }
|
|
64
|
+
},
|
|
65
|
+
install: {
|
|
66
|
+
where: '在 Claude Code 里',
|
|
67
|
+
commands: ['/plugin install kioku --marketplace lonelyman0108/kioku-plugins'],
|
|
68
|
+
after: '启用时填 Kioku 的地址与访问密钥(管理界面的应用页签发),新开会话生效',
|
|
69
|
+
},
|
|
70
|
+
source: 'claude-code',
|
|
25
71
|
// 应用的运行时要是这个,服务端才按这个平台给注入
|
|
26
72
|
runtimeFamily: 'claudecode',
|
|
27
73
|
// 这个平台的会话里有的环境变量,不写平台时靠它认出来
|
|
28
74
|
detect: (env) => env.CLAUDECODE === '1',
|
|
29
75
|
// 用户级的设置文件
|
|
30
|
-
settingsFile: (env) => join(env
|
|
76
|
+
settingsFile: (env) => join(claudeHome(env), 'settings.json'),
|
|
31
77
|
memory: {
|
|
32
78
|
name: '自动记忆(auto memory)',
|
|
33
79
|
// 停用:用户设置里把 autoMemoryEnabled 设为 false
|
|
@@ -46,16 +92,20 @@ const claudeCode = {
|
|
|
46
92
|
}
|
|
47
93
|
return settings?.autoMemoryEnabled === false ? '用户设置' : null
|
|
48
94
|
},
|
|
49
|
-
//
|
|
50
|
-
|
|
95
|
+
// 又在哪份项目设置里启用了(相对项目目录的路径):当前项目的设置优先于用户设置。别处(托管的设置)查不到
|
|
96
|
+
enabledIn: async (env, cwd) => {
|
|
51
97
|
// 环境变量停用着时,设置里写什么都不生效
|
|
52
98
|
if (TRUTHY.test((env.CLAUDE_CODE_DISABLE_AUTO_MEMORY ?? '').trim())) return null
|
|
53
99
|
for (const name of PROJECT_SETTINGS) {
|
|
54
|
-
if ((await settingOf(join(cwd, name), 'autoMemoryEnabled')) === true)
|
|
55
|
-
return `项目的 ${name} `
|
|
100
|
+
if ((await settingOf(join(cwd, name), 'autoMemoryEnabled')) === true) return name
|
|
56
101
|
}
|
|
57
102
|
return null
|
|
58
103
|
},
|
|
104
|
+
// 同上,给提示用的说法
|
|
105
|
+
enabledBy: async (env, cwd) => {
|
|
106
|
+
const name = await claudeCode.memory.enabledIn(env, cwd)
|
|
107
|
+
return name ? `项目的 ${name} ` : null
|
|
108
|
+
},
|
|
59
109
|
},
|
|
60
110
|
// 插件是否在用:这个会话里钩子已经配好了访问密钥文件,或者用户设置的 enabledPlugins 里有以「kioku@」开头、
|
|
61
111
|
// 值为 true 的一项。项目级的设置里启用的认不出来,所以认不出时只提醒、不算有问题
|
|
@@ -67,7 +117,98 @@ const claudeCode = {
|
|
|
67
117
|
pluginHint: '在 Claude Code 里用 /plugin 安装并启用 kioku',
|
|
68
118
|
}
|
|
69
119
|
|
|
70
|
-
|
|
120
|
+
const codex = {
|
|
121
|
+
name: 'Codex',
|
|
122
|
+
runtimeFamily: 'codex',
|
|
123
|
+
command: () => 'codex',
|
|
124
|
+
home: codexHome,
|
|
125
|
+
status: statusCodex,
|
|
126
|
+
install: {
|
|
127
|
+
commands: [
|
|
128
|
+
'codex plugin marketplace add lonelyman0108/kioku-plugins',
|
|
129
|
+
'codex plugin add kioku@kioku',
|
|
130
|
+
],
|
|
131
|
+
after: '打开 codex,在 /hooks 里信任 kioku 的三个钩子,新开会话生效',
|
|
132
|
+
},
|
|
133
|
+
// Codex 的会话里没有可靠的标记,要写明平台
|
|
134
|
+
detect: () => false,
|
|
135
|
+
// 地址与访问密钥放在本机的文件里(profile.mjs);readConfig 读出来给 doctor、login、import 用
|
|
136
|
+
readConfig: (env) => readProfile('codex', env),
|
|
137
|
+
setup: setupCodex,
|
|
138
|
+
// kioku login 申请之前先做的检查
|
|
139
|
+
preflight: preflightCodex,
|
|
140
|
+
inspect: inspectCodex,
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const pi = {
|
|
144
|
+
name: 'pi',
|
|
145
|
+
runtimeFamily: 'pi',
|
|
146
|
+
command: () => 'pi',
|
|
147
|
+
home: piHome,
|
|
148
|
+
status: statusPi,
|
|
149
|
+
install: {
|
|
150
|
+
commands: ['pi install git:github.com/lonelyman0108/kioku-plugins'],
|
|
151
|
+
after: '新开 pi 会话(或 /reload)生效',
|
|
152
|
+
},
|
|
153
|
+
detect: () => false,
|
|
154
|
+
readConfig: (env) => readProfile('pi', env),
|
|
155
|
+
setup: setupPi,
|
|
156
|
+
inspect: inspectPi,
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const hermes = {
|
|
160
|
+
name: 'Hermes',
|
|
161
|
+
runtimeFamily: 'hermes',
|
|
162
|
+
command: (env) => env.KIOKU_HERMES_BIN || 'hermes',
|
|
163
|
+
home: hermesHome,
|
|
164
|
+
status: statusHermes,
|
|
165
|
+
install: {
|
|
166
|
+
commands: ['hermes plugins install lonelyman0108/kioku-plugins/plugins/hermes --enable'],
|
|
167
|
+
after: '新开 Hermes 会话生效',
|
|
168
|
+
},
|
|
169
|
+
source: 'hermes',
|
|
170
|
+
detect: () => false,
|
|
171
|
+
// 地址与访问密钥在 Hermes 自己的 .env 里
|
|
172
|
+
readConfig: readHermesConfig,
|
|
173
|
+
setup: setupHermes,
|
|
174
|
+
preflight: preflightHermes,
|
|
175
|
+
inspect: inspectHermes,
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const openclaw = {
|
|
179
|
+
name: 'OpenClaw',
|
|
180
|
+
runtimeFamily: 'openclaw',
|
|
181
|
+
command: (env) => env.KIOKU_OPENCLAW_BIN || 'openclaw',
|
|
182
|
+
home: (env) => join(env.OPENCLAW_HOME || homedir(), '.openclaw'),
|
|
183
|
+
status: statusOpenclaw,
|
|
184
|
+
install: {
|
|
185
|
+
commands: ['openclaw plugins install npm:@kioku-memory/openclaw', 'openclaw gateway restart'],
|
|
186
|
+
after: '重启网关之后生效',
|
|
187
|
+
},
|
|
188
|
+
source: 'openclaw',
|
|
189
|
+
detect: () => false,
|
|
190
|
+
readConfig: (env) => readProfile('openclaw', env),
|
|
191
|
+
setup: setupOpenclaw,
|
|
192
|
+
inspect: inspectOpenclaw,
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const dsh = {
|
|
196
|
+
name: 'DeepSeek Harness',
|
|
197
|
+
runtimeFamily: 'dsh',
|
|
198
|
+
command: () => 'dsh',
|
|
199
|
+
home: dshHome,
|
|
200
|
+
status: statusDsh,
|
|
201
|
+
install: {
|
|
202
|
+
commands: ['dsh plugin --profile <profile> add github:lonelyman0108/kioku-plugins'],
|
|
203
|
+
after: '<profile> 换成要用的 profile(web、tui 这些各装一次),重启 dsh 生效',
|
|
204
|
+
},
|
|
205
|
+
detect: () => false,
|
|
206
|
+
readConfig: (env) => readProfile('dsh', env),
|
|
207
|
+
setup: setupDsh,
|
|
208
|
+
inspect: inspectDsh,
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export const PLATFORMS = { 'claude-code': claudeCode, codex, pi, hermes, openclaw, dsh }
|
|
71
212
|
|
|
72
213
|
export function platformNames() {
|
|
73
214
|
return Object.keys(PLATFORMS).join('、')
|
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/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
|
+
}
|
package/lib/setup.mjs
CHANGED
|
@@ -1,126 +1,84 @@
|
|
|
1
|
-
// kioku setup
|
|
1
|
+
// kioku setup:把平台交给 Kioku 接管。平台有自己的一套步骤时(codex)交给它,否则按下面通用的做法:
|
|
2
|
+
// 停用平台自带的长期记忆,只改平台的用户设置里的那几项,
|
|
2
3
|
// 改之前显示要改什么、留一份备份;--undo 只把这几项改回去,不动设置里的其他内容(文件会按 JSON 重新排版)
|
|
3
4
|
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import { dirname } from 'node:path'
|
|
8
|
-
|
|
9
|
-
import { errorKind, KiokuFailure } from './http.mjs'
|
|
5
|
+
import { readSettings, writeSettings } from './files.mjs'
|
|
6
|
+
import { deviceLogin } from './login.mjs'
|
|
7
|
+
import { plain } from './text.mjs'
|
|
10
8
|
import { platformNames, PLATFORMS } from './platforms.mjs'
|
|
9
|
+
import { readSecret } from './secret.mjs'
|
|
11
10
|
import { UsageError } from './usage.mjs'
|
|
12
11
|
|
|
13
|
-
export
|
|
12
|
+
export { readSettings, writeSettings }
|
|
13
|
+
|
|
14
|
+
export const SETUP_USAGE = `用法:kioku setup <平台> [--dry-run] [--undo] [--server-url <地址>] [--no-check]
|
|
14
15
|
|
|
15
|
-
|
|
16
|
+
把平台交给 Kioku 接管:停用平台自带的长期记忆;没有自己的密钥存储的平台(codex、pi、hermes、openclaw、dsh)再写下服务地址与访问密钥。
|
|
16
17
|
|
|
17
|
-
<平台>
|
|
18
|
-
--dry-run
|
|
19
|
-
--undo
|
|
18
|
+
<平台> ${platformNames()}
|
|
19
|
+
--dry-run 只显示要改什么,不写文件
|
|
20
|
+
--undo 改回去:重新启用平台自带的长期记忆,删掉写下的地址与访问密钥
|
|
21
|
+
--server-url <地址> Kioku 的服务地址,例如 https://kioku.example.com(codex、pi、hermes、openclaw、dsh 用;也可以用 KIOKU_SERVER_URL)
|
|
22
|
+
--no-check 不先连一次 Kioku 核对地址与访问密钥(codex、pi、hermes、openclaw、dsh 用)
|
|
20
23
|
|
|
21
|
-
|
|
22
|
-
|
|
24
|
+
访问密钥不写在命令行上:从 KIOKU_API_KEY 读,或者从标准输入读;在终端里运行时会提示输入(不回显),
|
|
25
|
+
直接回车就改用浏览器授权(同 kioku login)。
|
|
26
|
+
只改平台设置里和 Kioku 有关的几项,第一次改之前把原来的文件备份成同目录下的 <文件名>.kioku-backup(已有备份时不覆盖)。
|
|
27
|
+
改完新开会话生效。本地已有的记忆文件不会被删掉。
|
|
23
28
|
`
|
|
24
29
|
|
|
30
|
+
// 给各平台的 setup 用的浏览器授权:按平台的运行时申请
|
|
31
|
+
function browserLogin(out) {
|
|
32
|
+
return ({ url, id }) => deviceLogin({ url, runtimeFamily: PLATFORMS[id].runtimeFamily }, { out })
|
|
33
|
+
}
|
|
34
|
+
|
|
25
35
|
export function parseSetupArgs(argv) {
|
|
26
|
-
const options = { dryRun: false, undo: false }
|
|
36
|
+
const options = { dryRun: false, undo: false, check: true, serverUrl: undefined }
|
|
27
37
|
const names = []
|
|
28
|
-
for (
|
|
38
|
+
for (let i = 0; i < argv.length; i++) {
|
|
39
|
+
const arg = argv[i]
|
|
29
40
|
if (arg === '--dry-run') options.dryRun = true
|
|
30
41
|
else if (arg === '--undo') options.undo = true
|
|
31
|
-
else if (arg
|
|
42
|
+
else if (arg === '--no-check') options.check = false
|
|
43
|
+
else if (arg === '--server-url') {
|
|
44
|
+
options.serverUrl = argv[++i]
|
|
45
|
+
if (!options.serverUrl) throw new UsageError('--server-url 后面要写地址')
|
|
46
|
+
} else if (arg.startsWith('-')) throw new UsageError(`不认识的选项 ${arg}`)
|
|
32
47
|
else names.push(arg)
|
|
33
48
|
}
|
|
34
49
|
if (names.length !== 1) throw new UsageError('要写一个平台')
|
|
35
50
|
if (!Object.hasOwn(PLATFORMS, names[0])) {
|
|
36
51
|
throw new UsageError(`不认识的平台 ${names[0]},可以用的:${platformNames()}`)
|
|
37
52
|
}
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
export async function readSettings(file) {
|
|
44
|
-
let text
|
|
45
|
-
try {
|
|
46
|
-
text = await readFile(file, 'utf8')
|
|
47
|
-
} catch (err) {
|
|
48
|
-
if (err?.code === 'ENOENT') return { settings: {}, text: null }
|
|
49
|
-
throw new KiokuFailure(`无法读取 ${file}(${errorKind(err)})`)
|
|
50
|
-
}
|
|
51
|
-
// 开头的 BOM 不算内容
|
|
52
|
-
const body = text.replace(/^\uFEFF/, '')
|
|
53
|
-
if (!body.trim()) return { settings: {}, text }
|
|
54
|
-
let settings
|
|
55
|
-
try {
|
|
56
|
-
settings = JSON.parse(body)
|
|
57
|
-
} catch {
|
|
58
|
-
settings = null
|
|
59
|
-
}
|
|
60
|
-
if (settings === null || typeof settings !== 'object' || Array.isArray(settings)) {
|
|
61
|
-
throw new KiokuFailure(`${file} 不是 JSON 对象,没有改动它`)
|
|
53
|
+
const platform = PLATFORMS[names[0]]
|
|
54
|
+
if (!platform.setup && (options.serverUrl !== undefined || !options.check)) {
|
|
55
|
+
throw new UsageError(
|
|
56
|
+
`${platform.name} 的地址与访问密钥在它自己的插件配置里填,不用 --server-url、--no-check`,
|
|
57
|
+
)
|
|
62
58
|
}
|
|
63
|
-
return {
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
// 沿用原文件的缩进(取第一处,没有就用两个空格)、换行符和结尾有没有换行;别的排版按 JSON 的默认写法
|
|
67
|
-
function serialize(settings, text) {
|
|
68
|
-
const indent = /\n([ \t]+)"/.exec(text ?? '')?.[1] ?? ' '
|
|
69
|
-
const eol = text?.includes('\r\n') ? '\r\n' : '\n'
|
|
70
|
-
const tail = text === null || !text.trim() || /\n$/.test(text) ? eol : ''
|
|
71
|
-
return JSON.stringify(settings, null, indent).replaceAll('\n', eol) + tail
|
|
59
|
+
return { ...options, platform: names[0] }
|
|
72
60
|
}
|
|
73
61
|
|
|
74
62
|
function shown(value) {
|
|
75
63
|
return value === undefined ? '(未设置)' : JSON.stringify(value)
|
|
76
64
|
}
|
|
77
65
|
|
|
78
|
-
// 写回设置文件,返回这次有没有留备份。
|
|
79
|
-
// - 设置文件是符号链接时改它指向的文件,不把链接换成普通文件。
|
|
80
|
-
// - 先写临时文件再改名:写到一半被打断时原来的设置还在;失败时临时文件删掉。
|
|
81
|
-
// - 改名之前再读一次,和开始时读到的不一样就不写:别的程序刚改过,写下去会盖掉它的改动。
|
|
82
|
-
// - 备份只留第一份:之后再改时不覆盖,最早的原文件才留得住。
|
|
83
|
-
// 权限沿用原文件的,新建的只给本人
|
|
84
|
-
export async function writeSettings(file, settings, text) {
|
|
85
|
-
let target = file
|
|
86
|
-
let temp
|
|
87
|
-
try {
|
|
88
|
-
if (text === null) await mkdir(dirname(file), { recursive: true })
|
|
89
|
-
else target = await realpath(file)
|
|
90
|
-
const mode = text === null ? 0o600 : (await stat(target)).mode & 0o777
|
|
91
|
-
temp = `${target}.${randomUUID()}.tmp`
|
|
92
|
-
await writeFile(temp, serialize(settings, text), { mode, flag: 'wx' })
|
|
93
|
-
const current = await readFile(target, 'utf8').catch((err) => {
|
|
94
|
-
if (err?.code === 'ENOENT') return null
|
|
95
|
-
throw err
|
|
96
|
-
})
|
|
97
|
-
if (current !== text) {
|
|
98
|
-
throw new KiokuFailure(`${file} 刚被别的程序改过,没有写入:重新运行一次`)
|
|
99
|
-
}
|
|
100
|
-
let backedUp = false
|
|
101
|
-
if (text !== null) {
|
|
102
|
-
try {
|
|
103
|
-
await copyFile(target, `${file}.kioku-backup`, constants.COPYFILE_EXCL)
|
|
104
|
-
backedUp = true
|
|
105
|
-
} catch (err) {
|
|
106
|
-
if (err?.code !== 'EEXIST') throw err
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
await rename(temp, target)
|
|
110
|
-
return backedUp
|
|
111
|
-
} catch (err) {
|
|
112
|
-
if (temp) await rm(temp, { force: true }).catch(() => {})
|
|
113
|
-
if (err instanceof KiokuFailure) throw err
|
|
114
|
-
throw new KiokuFailure(`无法写入 ${file}(${errorKind(err)})`)
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
|
|
118
66
|
export async function setup(
|
|
119
67
|
argv,
|
|
120
|
-
{
|
|
68
|
+
{
|
|
69
|
+
env = process.env,
|
|
70
|
+
out = process.stdout,
|
|
71
|
+
cwd = process.cwd(),
|
|
72
|
+
readKey = readSecret,
|
|
73
|
+
// 在终端里运行、没给访问密钥时可以改用浏览器授权;不在终端里(管道、agent 的命令)时没有;传 null 是明说不要
|
|
74
|
+
login = process.stdin.isTTY ? browserLogin(out) : null,
|
|
75
|
+
} = {},
|
|
121
76
|
) {
|
|
122
|
-
const
|
|
77
|
+
const options = parseSetupArgs(argv)
|
|
78
|
+
const { platform: id, dryRun, undo } = options
|
|
123
79
|
const platform = PLATFORMS[id]
|
|
80
|
+
// 有自己的一套步骤的平台
|
|
81
|
+
if (platform.setup) return platform.setup(options, { env, out, cwd, readKey, plain, login })
|
|
124
82
|
const { memory } = platform
|
|
125
83
|
const file = platform.settingsFile(env)
|
|
126
84
|
const { settings, text } = await readSettings(file)
|