@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
package/lib/connect.mjs DELETED
@@ -1,152 +0,0 @@
1
- // 把几个平台接到 Kioku:拿到访问密钥之后交给各平台的 kioku setup 写下(核对、写文件都照它的规矩)。
2
- // 向导走浏览器授权,几个平台一起申请、只确认一次;服务端不认这种写法时逐个平台申请。
3
- // kioku install 的访问密钥从环境变量来,直接写下。插件不替用户装,只列出要运行的命令
4
-
5
- import { KiokuFailure } from './http.mjs'
6
- import { deviceLogin, deviceLoginMany, LegacyServer, MAX_PLATFORMS } from './login.mjs'
7
- import { PLATFORMS } from './platforms.mjs'
8
- import { plain } from './text.mjs'
9
-
10
- // 访问密钥已经签发、却没有写下来:说清楚,别让它悄悄留着。kioku login 也用它
11
- export function orphanHint(app) {
12
- const name = app?.name ? `(应用 ${plain(app.name)})` : ''
13
- return `访问密钥已经签发、但没有写下:到管理界面的应用页吊销它${name},解决上面的问题后重新运行`
14
- }
15
-
16
- // 用给定的地址与访问密钥配好一个平台。setup 的输出写到 out;hints 为假时不打印「接下来装上」,
17
- // 由调用方统一列出(向导与 kioku install),kioku login 只配一个平台,照旧打印
18
- export function configure(id, { url, key }, { env, out, cwd }, { hints = false } = {}) {
19
- return PLATFORMS[id].setup(
20
- { serverUrl: url, dryRun: false, undo: false, check: true },
21
- { env, out, cwd, readKey: async () => key, plain, login: null, hints },
22
- )
23
- }
24
-
25
- // 签发好的访问密钥写下;写不下时提醒去吊销
26
- async function settle(id, key, app, io) {
27
- io.out.write(`\n${PLATFORMS[id].name}\n`)
28
- try {
29
- await configure(id, { url: io.url, key }, io)
30
- return { id, status: 'connected', app }
31
- } catch (err) {
32
- // 别的错误照旧抛出(由入口报内部错误),不当成一个平台的失败吞掉
33
- if (!(err instanceof KiokuFailure)) throw err
34
- return { id, status: 'failed', reason: `${err.message}。${orphanHint(app)}` }
35
- }
36
- }
37
-
38
- // 用浏览器授权把这几个平台接到 url。返回每个平台的结果(按 ids 的顺序):
39
- // { id, status: 'connected' | 'skipped' | 'denied' | 'failed', reason?, app? }
40
- export async function connectPlatforms(
41
- { url, ids },
42
- { env, out, cwd, open, browser = true, clientName, sleep, now },
43
- ) {
44
- const io = { env, out, cwd, url }
45
- const login = { out, open, browser, sleep, now, ...(clientName ? { clientName } : {}) }
46
- const results = new Map()
47
- // 申请之前先看各平台的配置写不写得进去:访问密钥只在签发时给一次
48
- const ready = []
49
- for (const id of ids) {
50
- try {
51
- await PLATFORMS[id].preflight?.({ env, cwd })
52
- ready.push(id)
53
- } catch (err) {
54
- if (!(err instanceof KiokuFailure)) throw err
55
- results.set(id, { id, status: 'failed', reason: err.message })
56
- }
57
- }
58
- // 一次最多 MAX_PLATFORMS 个:多了分批,每批确认一次,前一批签发的先写下再申请下一批
59
- const batches = []
60
- for (let i = 0; i < ready.length; i += MAX_PLATFORMS) {
61
- batches.push(ready.slice(i, i + MAX_PLATFORMS))
62
- }
63
- if (batches.length > 1) {
64
- out.write(`一次最多申请 ${MAX_PLATFORMS} 个平台:分 ${batches.length} 批,每批确认一次\n`)
65
- }
66
- let legacy = false
67
- for (const batch of batches) {
68
- out.write(
69
- `这次申请 ${batch.length} 个平台:${batch.map((id) => PLATFORMS[id].name).join('、')}\n`,
70
- )
71
- let answers
72
- try {
73
- answers = await deviceLoginMany(
74
- { url, runtimeFamilies: batch.map((id) => PLATFORMS[id].runtimeFamily) },
75
- login,
76
- )
77
- } catch (err) {
78
- if (err instanceof LegacyServer) {
79
- legacy = true
80
- out.write(`${err.message}\n`)
81
- break
82
- }
83
- if (!(err instanceof KiokuFailure)) throw err
84
- for (const id of batch) results.set(id, { id, status: 'failed', reason: err.message })
85
- continue
86
- }
87
- for (const id of batch) {
88
- const answer = answers.find((item) => item.runtimeFamily === PLATFORMS[id].runtimeFamily)
89
- if (answer?.status === 'issued') results.set(id, await settle(id, answer.key, answer.app, io))
90
- else if (answer?.status === 'denied') {
91
- results.set(id, { id, status: 'denied', reason: answer.reason || '没有签发' })
92
- } else results.set(id, { id, status: 'skipped', reason: '确认页上没有勾选' })
93
- }
94
- }
95
- if (legacy) {
96
- // 旧的服务端:还没有结果的平台逐个申请,每个确认一次;一个不成不影响下一个
97
- for (const id of ready.filter((item) => !results.has(item))) {
98
- out.write(`\n${PLATFORMS[id].name}:浏览器授权\n`)
99
- let key
100
- try {
101
- key = await deviceLogin({ url, runtimeFamily: PLATFORMS[id].runtimeFamily }, login)
102
- } catch (err) {
103
- if (!(err instanceof KiokuFailure)) throw err
104
- results.set(id, { id, status: 'failed', reason: err.message })
105
- continue
106
- }
107
- results.set(id, await settle(id, key, null, io))
108
- }
109
- }
110
- return ids.map((id) => results.get(id))
111
- }
112
-
113
- const STATUS_NAMES = {
114
- connected: '已接入',
115
- manual: '待完成',
116
- skipped: '跳过',
117
- denied: '被拒绝',
118
- failed: '失败',
119
- }
120
-
121
- // 结果的文字:按状态分组,一组一行,原因跟在平台名后面
122
- export function resultsText(results) {
123
- const lines = []
124
- for (const status of Object.keys(STATUS_NAMES)) {
125
- const group = results.filter((item) => item.status === status)
126
- if (!group.length) continue
127
- const names = group.map((item) => {
128
- const detail = item.reason ?? (item.app?.name ? `应用 ${plain(item.app.name)}` : '')
129
- return detail ? `${PLATFORMS[item.id].name}(${detail})` : PLATFORMS[item.id].name
130
- })
131
- lines.push(`${STATUS_NAMES[status]}:${names.join('、')}`)
132
- }
133
- return lines.join('\n')
134
- }
135
-
136
- // 这几个平台里还要自己装插件的(查得到装好了的不列),每个平台一段:在哪里运行、可以直接复制的命令、之后要做的事。
137
- // 访问密钥在插件配置里填的平台(Claude Code),给了 url 时写明要填的服务地址
138
- export async function pluginSteps(ids, { env, cwd, url }) {
139
- const blocks = []
140
- for (const id of ids) {
141
- const platform = PLATFORMS[id]
142
- const status = await platform.status({ env, cwd }).catch(() => ({ plugin: null }))
143
- if (status.plugin === true) continue
144
- const { where = '在终端里', commands, after } = platform.install
145
- const lines = [`${platform.name}(${where}运行)`, ...commands.map((line) => ` ${line}`)]
146
- if (!platform.setup && url) lines.push(` 服务地址填:${url}`)
147
- lines.push(` 然后:${after}`)
148
- blocks.push(lines.join('\n'))
149
- }
150
- if (!blocks.length) return ''
151
- return `接下来自己装插件,装好之后再运行 kioku 看状态:\n\n${blocks.join('\n\n')}`
152
- }
package/lib/doctor.mjs DELETED
@@ -1,158 +0,0 @@
1
- // kioku doctor:检查地址与访问密钥能不能用、访问密钥的权限,以及平台这一边配好没有。
2
- // 每项一行:✓ 正常,! 要留意,✗ 有问题;有 ✗ 时退出码为 1
3
-
4
- import { loadConfig, NotConfigured } from './config.mjs'
5
- import { whoami } from './api.mjs'
6
- import { scanConflicts } from './conflicts.mjs'
7
- import { failureText, KiokuFailure } from './http.mjs'
8
- import { detectPlatform, platformNames, PLATFORMS } from './platforms.mjs'
9
- import { readSettings } from './files.mjs'
10
- import { plain, shownUrl } from './text.mjs'
11
- import { UsageError } from './usage.mjs'
12
-
13
- export const DOCTOR_USAGE = `用法:kioku doctor [平台]
14
-
15
- 检查 Kioku 的地址与访问密钥、访问密钥的权限,以及平台的配置(插件是否启用、自带的长期记忆是否已停用)。
16
-
17
- [平台] ${platformNames()};不写时按当前所在的会话认,认不出就只查地址与访问密钥
18
-
19
- 有问题的项以 ✗ 开头,这时退出码为 1。
20
- `
21
-
22
- // 与管理界面的用词一致
23
- const LAYERS = {
24
- core: '通用',
25
- persona: '人格',
26
- app: '应用',
27
- user: '本人',
28
- subject: '联系人',
29
- episode: '会话',
30
- }
31
- const SENSITIVITIES = { public: '公开', internal: '内部', private: '私密', secret: '机密' }
32
- const CAPABILITIES = { none: '不可用', use: '取用', manage: '管理' }
33
-
34
- function named(names, value) {
35
- return Object.hasOwn(names, value) ? names[value] : plain(value)
36
- }
37
-
38
- function layersText(layers) {
39
- if (!Array.isArray(layers) || !layers.length) return '无'
40
- return layers.map((layer) => named(LAYERS, layer)).join('、')
41
- }
42
-
43
- export function parseDoctorArgs(argv) {
44
- const names = []
45
- for (const arg of argv) {
46
- if (arg.startsWith('-')) throw new UsageError(`不认识的选项 ${arg}`)
47
- names.push(arg)
48
- }
49
- if (names.length > 1) throw new UsageError('最多写一个平台')
50
- if (names.length && !Object.hasOwn(PLATFORMS, names[0])) {
51
- throw new UsageError(`不认识的平台 ${names[0]},可以用的:${platformNames()}`)
52
- }
53
- return { platform: names[0] ?? null }
54
- }
55
-
56
- export async function doctor(
57
- argv,
58
- { env = process.env, out = process.stdout, cwd = process.cwd() } = {},
59
- ) {
60
- const id = parseDoctorArgs(argv).platform ?? detectPlatform(env)
61
- const platform = id ? PLATFORMS[id] : null
62
- let failed = false
63
- const ok = (text) => out.write(`✓ ${text}\n`)
64
- const warn = (text) => out.write(`! ${text}\n`)
65
- const bad = (text) => {
66
- failed = true
67
- out.write(`✗ ${text}\n`)
68
- }
69
-
70
- let who = null
71
- try {
72
- // 平台把地址与访问密钥放在自己的文件里时先读它,没有再看环境变量
73
- const profile = platform?.readConfig ? await platform.readConfig(env) : null
74
- let config = profile
75
- if (!config) {
76
- try {
77
- config = await loadConfig(env)
78
- } catch (err) {
79
- // 这个平台有自己放配置的地方、却什么都没配:说怎么配,不说别的平台的做法。
80
- // 环境变量里配了但不对的(地址无效、访问密钥文件读不了)照原样报
81
- if (platform?.readConfig && err instanceof NotConfigured) {
82
- throw new KiokuFailure(`还没有给 ${platform.name} 配过:运行 kioku setup ${id}`)
83
- }
84
- throw err
85
- }
86
- }
87
- ok(`地址 ${shownUrl(config.url)}${profile ? `(${profile.file})` : ''}`)
88
- who = await whoami(config)
89
- } catch (err) {
90
- bad(failureText(err))
91
- }
92
- if (who) {
93
- const { app, scopes } = who
94
- ok(
95
- `访问密钥可用:应用 ${plain(app.name)}(${plain(app.slug)}),运行时 ${plain(app.runtimeFamily)}`,
96
- )
97
- out.write(` 读:${layersText(scopes.readLayers)}\n`)
98
- out.write(` 写:${layersText(scopes.writeLayers)}\n`)
99
- out.write(` 最高敏感级:${named(SENSITIVITIES, scopes.maxSensitivity)}\n`)
100
- out.write(` 凭据:${named(CAPABILITIES, scopes.credentials ?? 'none')}\n`)
101
- if (platform && app.runtimeFamily !== platform.runtimeFamily) {
102
- warn(
103
- `这个应用的运行时不是 ${platform.runtimeFamily},注入的内容不按 ${platform.name} 的格式:在管理界面为 ${platform.name} 另建一个应用`,
104
- )
105
- }
106
- }
107
-
108
- if (!platform) {
109
- out.write(`没有认出平台,只查了地址与访问密钥;要查平台的配置,写上平台:${platformNames()}\n`)
110
- return failed ? 1 : 0
111
- }
112
- const note = (text) => out.write(` ${text}\n`)
113
- const checkConflicts = async () => {
114
- const conflicts = await scanConflicts(id, { env, cwd }).catch(() => [])
115
- if (!conflicts.length) return
116
- for (const item of conflicts) {
117
- const hint = item.hint ? `(${item.hint})` : ''
118
- warn(`发现冲突的记忆工具(${item.toolName}):${item.summary}${hint}`)
119
- }
120
- if (conflicts.some((item) => item.removable)) {
121
- note(`清理冲突:运行 kioku clean ${id}`)
122
- }
123
- }
124
-
125
- if (platform.inspect) {
126
- try {
127
- await platform.inspect({ env, cwd }, { ok, warn, bad, note })
128
- await checkConflicts()
129
- } catch (err) {
130
- bad(failureText(err))
131
- }
132
- return failed ? 1 : 0
133
- }
134
- let settings = null
135
- try {
136
- settings = (await readSettings(platform.settingsFile(env))).settings
137
- } catch (err) {
138
- bad(failureText(err))
139
- }
140
- if (settings) {
141
- if (platform.pluginActive(settings, env)) ok(`${platform.name} 的 kioku 插件已启用`)
142
- else warn(`用户设置里没有启用 ${platform.name} 的 kioku 插件:${platform.pluginHint}`)
143
- const by = platform.memory.disabledBy(settings, env)
144
- const again = by ? await platform.memory.enabledBy(env, cwd) : null
145
- if (again) {
146
- warn(
147
- `${platform.name} 的${platform.memory.name}在${by}里停用了,${again}又启用了它:要在那里一起改`,
148
- )
149
- } else if (by) ok(`${platform.name} 的${platform.memory.name}已停用(${by})`)
150
- else {
151
- warn(
152
- `${platform.name} 的${platform.memory.name}还开着,会和 Kioku 各记一份:运行 kioku setup ${id} 停用它`,
153
- )
154
- }
155
- }
156
- await checkConflicts()
157
- return failed ? 1 : 0
158
- }
package/lib/dsh.mjs DELETED
@@ -1,82 +0,0 @@
1
- // DeepSeek Harness 这个平台的 kioku setup 与 kioku doctor。
2
- // 它没有自带的长期记忆要停用;插件与 MCP 客户端都由本仓库的补丁装上,读本机文件里的服务地址与访问密钥。
3
- // 所以 setup 只做一件事:把服务地址与访问密钥写进本机的文件
4
-
5
- import { readdir } from 'node:fs/promises'
6
- import { homedir } from 'node:os'
7
- import { join } from 'node:path'
8
-
9
- import { readSettings } from './files.mjs'
10
- import { profileFile, readProfile, removeProfile, writeProfile } from './profile.mjs'
11
- import { plain } from './text.mjs'
12
- import { resolveTarget } from './target.mjs'
13
-
14
- const PACKAGE = 'kioku-plugins'
15
- const SOURCE = 'github:lonelyman0108/kioku-plugins'
16
-
17
- export function dshHome(env) {
18
- return env.DSH_HOME || join(homedir(), '.dsh')
19
- }
20
-
21
- // 装了本仓库这个包的 profile 的名字;没有 profile 目录时为空
22
- async function installedProfiles(env) {
23
- const root = join(dshHome(env), 'profiles')
24
- const names = await readdir(root).catch(() => [])
25
- const found = []
26
- for (const name of names.sort()) {
27
- const { settings } = await readSettings(join(root, name, 'package.json')).catch(() => ({}))
28
- const bundles = settings?.dsh?.profile?.bundles
29
- if (Array.isArray(bundles) && bundles.includes(PACKAGE)) found.push(name)
30
- }
31
- return found
32
- }
33
-
34
- const installHint = `dsh plugin --profile <profile> add ${SOURCE}`
35
-
36
- export async function setupDsh(options, io) {
37
- const { env, out } = io
38
- const profile = profileFile('dsh', env)
39
- if (options.undo) {
40
- if (options.dryRun) out.write(`${profile}:删掉\n没有写入(--dry-run)\n`)
41
- else if (await removeProfile('dsh', env)) out.write(`已删掉 ${profile}\n`)
42
- else out.write(`${profile} 本来就没有\n`)
43
- out.write(`插件要另外卸载:dsh plugin --profile <profile> remove ${PACKAGE}\n`)
44
- return 0
45
- }
46
- const { url, key, saved } = await resolveTarget(
47
- { id: 'dsh', name: 'DeepSeek Harness' },
48
- options,
49
- io,
50
- )
51
- const same = Boolean(saved && saved.url === url && saved.key === key)
52
- if (same) out.write(`${profile} 不用改\n`)
53
- else out.write(`${profile}:写入服务地址与访问密钥(只给本人读写)\n`)
54
- if (options.dryRun) {
55
- out.write('没有写入(--dry-run)\n')
56
- return 0
57
- }
58
- if (!same) await writeProfile('dsh', { url, key }, env)
59
- const profiles = await installedProfiles(env)
60
- out.write('DeepSeek Harness 已配好,重启 dsh 后生效(读写记忆的工具在启动时连上)。\n')
61
- if (profiles.length) out.write(`装了插件的 profile:${profiles.map(plain).join('、')}\n`)
62
- else if (io.hints !== false) {
63
- out.write(`接下来给要用的 profile 装上插件(web、tui 这些各装一次):${installHint}\n`)
64
- }
65
- return 0
66
- }
67
-
68
- export async function inspectDsh({ env }, { ok, warn, note }) {
69
- const profile = await readProfile('dsh', env).catch(() => null)
70
- if (!profile)
71
- warn('没有 kioku setup dsh 写下的地址与访问密钥,插件不会生效:运行 kioku setup dsh')
72
- const profiles = await installedProfiles(env)
73
- if (profiles.length) ok(`装了 kioku 插件的 profile:${profiles.map(plain).join('、')}`)
74
- else warn(`没有哪个 profile 装了 kioku 的插件:${installHint}`)
75
- note('插件按 profile 装:没装的 profile 里没有长期记忆')
76
- ok('DeepSeek Harness 没有自带的长期记忆要停用')
77
- }
78
-
79
- // 给向导的面板:有没有哪个 profile 装了插件,dsh 没有自带的长期记忆
80
- export async function statusDsh({ env }) {
81
- return { plugin: (await installedProfiles(env)).length > 0, memory: 'none' }
82
- }
package/lib/files.mjs DELETED
@@ -1,92 +0,0 @@
1
- // kioku setup 读写平台设置文件的共用部分。设置文件是用户的,里面还有别的工具写的内容,平台自己也随时在改它,
2
- // 所以:读不懂的不动它,符号链接改它指向的文件,先写临时文件,改名之前确认没有别人刚改过,备份只留第一份
3
-
4
- import { randomUUID } from 'node:crypto'
5
- import { constants } from 'node:fs'
6
- import { copyFile, mkdir, readFile, realpath, rename, rm, stat, writeFile } from 'node:fs/promises'
7
- import { dirname } from 'node:path'
8
-
9
- import { errorKind, KiokuFailure } from './http.mjs'
10
-
11
- // 读文件的原文;没有这个文件时为 null
12
- export async function readText(file) {
13
- try {
14
- return await readFile(file, 'utf8')
15
- } catch (err) {
16
- if (err?.code === 'ENOENT') return null
17
- throw new KiokuFailure(`无法读取 ${file}(${errorKind(err)})`)
18
- }
19
- }
20
-
21
- // 读 JSON 的设置文件:没有这个文件、或者文件是空的,按空的设置;内容不是 JSON 对象时不动它,报错。
22
- // text 是读到的原文,没有这个文件时为 null
23
- export async function readSettings(file) {
24
- const text = await readText(file)
25
- if (text === null) return { settings: {}, text: null }
26
- // 开头的 BOM 不算内容
27
- const body = text.replace(/^\uFEFF/, '')
28
- if (!body.trim()) return { settings: {}, text }
29
- let settings
30
- try {
31
- settings = JSON.parse(body)
32
- } catch {
33
- settings = null
34
- }
35
- if (settings === null || typeof settings !== 'object' || Array.isArray(settings)) {
36
- throw new KiokuFailure(`${file} 不是 JSON 对象,没有改动它`)
37
- }
38
- return { settings, text }
39
- }
40
-
41
- // 沿用原文件的缩进(取第一处,没有就用两个空格)、换行符和结尾有没有换行;别的排版按 JSON 的默认写法
42
- export function serialize(settings, text) {
43
- const indent = /\n([ \t]+)"/.exec(text ?? '')?.[1] ?? ' '
44
- const eol = text?.includes('\r\n') ? '\r\n' : '\n'
45
- const tail = text === null || !text.trim() || /\n$/.test(text) ? eol : ''
46
- return JSON.stringify(settings, null, indent).replaceAll('\n', eol) + tail
47
- }
48
-
49
- // 把 body 写成设置文件的新内容,返回这次有没有留备份。text 是开始时读到的原文,没有这个文件时为 null。
50
- // - 设置文件是符号链接时改它指向的文件,不把链接换成普通文件。
51
- // - 先写临时文件再改名:写到一半被打断时原来的设置还在;失败时临时文件删掉。
52
- // - 改名之前再读一次,和开始时读到的不一样就不写:别的程序刚改过,写下去会盖掉它的改动。
53
- // - 备份只留第一份:之后再改时不覆盖,最早的原文件才留得住。原文里有不该多留一份的内容时(backup 为假)不备份。
54
- // 权限沿用原文件的,新建的只给本人
55
- export async function safeWrite(file, body, text, { backup = true } = {}) {
56
- let target = file
57
- let temp
58
- try {
59
- if (text === null) await mkdir(dirname(file), { recursive: true })
60
- else target = await realpath(file)
61
- const mode = text === null ? 0o600 : (await stat(target)).mode & 0o777
62
- temp = `${target}.${randomUUID()}.tmp`
63
- await writeFile(temp, body, { mode, flag: 'wx' })
64
- const current = await readFile(target, 'utf8').catch((err) => {
65
- if (err?.code === 'ENOENT') return null
66
- throw err
67
- })
68
- if (current !== text) {
69
- throw new KiokuFailure(`${file} 刚被别的程序改过,没有写入:重新运行一次`)
70
- }
71
- let backedUp = false
72
- if (text !== null && backup) {
73
- try {
74
- await copyFile(target, `${file}.kioku-backup`, constants.COPYFILE_EXCL)
75
- backedUp = true
76
- } catch (err) {
77
- if (err?.code !== 'EEXIST') throw err
78
- }
79
- }
80
- await rename(temp, target)
81
- return backedUp
82
- } catch (err) {
83
- if (temp) await rm(temp, { force: true }).catch(() => {})
84
- if (err instanceof KiokuFailure) throw err
85
- throw new KiokuFailure(`无法写入 ${file}(${errorKind(err)})`)
86
- }
87
- }
88
-
89
- // 写回 JSON 的设置文件
90
- export function writeSettings(file, settings, text) {
91
- return safeWrite(file, serialize(settings, text), text)
92
- }
package/lib/gemini.mjs DELETED
@@ -1,199 +0,0 @@
1
- // Gemini CLI 这个平台的 kioku setup 与 kioku doctor。
2
- // setup 做三件事:
3
- // 1. 把服务地址与访问密钥写进本机文件(只给本人读写,扩展的钩子读它);
4
- // 2. 在 ~/.gemini/settings.json 里写入 mcpServers.kioku;
5
- // 3. 把自带记忆工具 save_memory 加进 excludeTools 停用
6
-
7
- import { stat } from 'node:fs/promises'
8
- import { homedir } from 'node:os'
9
- import { join } from 'node:path'
10
-
11
- import { readSettings, safeWrite, serialize } from './files.mjs'
12
- import { KiokuFailure } from './http.mjs'
13
- import { profileFile, readProfile, removeProfile, writeProfile } from './profile.mjs'
14
- import { resolveTarget } from './target.mjs'
15
-
16
- export function geminiHome(env) {
17
- if (env.GEMINI_CLI_HOME) return join(env.GEMINI_CLI_HOME, '.gemini')
18
- return join(env.HOME || homedir(), '.gemini')
19
- }
20
-
21
- export function geminiSettingsFile(env) {
22
- return join(geminiHome(env), 'settings.json')
23
- }
24
-
25
- function checkStructure(settings, file) {
26
- if (
27
- settings.mcpServers !== undefined &&
28
- (settings.mcpServers === null ||
29
- typeof settings.mcpServers !== 'object' ||
30
- Array.isArray(settings.mcpServers))
31
- ) {
32
- throw new KiokuFailure(`${file} 里的 mcpServers 不是对象,没有改动它`)
33
- }
34
- if (settings.excludeTools !== undefined && !Array.isArray(settings.excludeTools)) {
35
- throw new KiokuFailure(`${file} 里的 excludeTools 不是数组,没有改动它`)
36
- }
37
- }
38
-
39
- function mcpEntry(url, key) {
40
- return {
41
- httpUrl: `${url}/v1/mcp`,
42
- headers: { Authorization: `Bearer ${key}` },
43
- }
44
- }
45
-
46
- function sameMcp(existing, wanted) {
47
- return (
48
- existing?.httpUrl === wanted.httpUrl &&
49
- existing?.headers?.Authorization === wanted.headers.Authorization
50
- )
51
- }
52
-
53
- function hasStoredKey(settings) {
54
- return Boolean(settings?.mcpServers?.kioku?.headers?.Authorization)
55
- }
56
-
57
- function buildSettings(settings, { url, key, undo }) {
58
- const next = { ...settings }
59
- if (undo) {
60
- if (
61
- settings.mcpServers &&
62
- typeof settings.mcpServers === 'object' &&
63
- Object.hasOwn(settings.mcpServers, 'kioku')
64
- ) {
65
- const mcp = { ...settings.mcpServers }
66
- delete mcp.kioku
67
- if (Object.keys(mcp).length) next.mcpServers = mcp
68
- else delete next.mcpServers
69
- }
70
- if (Array.isArray(settings.excludeTools) && settings.excludeTools.includes('save_memory')) {
71
- const filtered = settings.excludeTools.filter((tool) => tool !== 'save_memory')
72
- if (filtered.length) next.excludeTools = filtered
73
- else delete next.excludeTools
74
- }
75
- return next
76
- }
77
-
78
- next.mcpServers = { ...(settings.mcpServers ?? {}), kioku: mcpEntry(url, key) }
79
- const excludes = Array.isArray(settings.excludeTools) ? [...settings.excludeTools] : []
80
- if (!excludes.includes('save_memory')) excludes.push('save_memory')
81
- next.excludeTools = excludes
82
- return next
83
- }
84
-
85
- async function extensionInstalled(env, cwd) {
86
- for (const dir of [
87
- join(geminiHome(env), 'extensions', 'kioku'),
88
- join(cwd, '.gemini', 'extensions', 'kioku'),
89
- ]) {
90
- if ((await stat(join(dir, 'gemini-extension.json')).catch(() => null))?.isFile()) return true
91
- }
92
- return false
93
- }
94
-
95
- export async function preflightGemini({ env }) {
96
- const file = geminiSettingsFile(env)
97
- const { settings } = await readSettings(file)
98
- checkStructure(settings, file)
99
- }
100
-
101
- export async function setupGemini(options, io) {
102
- const { env, out, cwd } = io
103
- const profile = profileFile('gemini', env)
104
- const file = geminiSettingsFile(env)
105
-
106
- if (options.undo) {
107
- const { settings, text } = await readSettings(file)
108
- checkStructure(settings, file)
109
- const next = buildSettings(settings, { undo: true })
110
- if (JSON.stringify(settings) === JSON.stringify(next)) {
111
- if (text !== null) out.write(`${file} 不用改\n`)
112
- } else {
113
- out.write(`${file}:去掉 mcpServers.kioku,恢复 save_memory\n`)
114
- if (!options.dryRun) {
115
- // 原文件里带着访问密钥时不留备份
116
- await safeWrite(file, serialize(next, text), text, { backup: !hasStoredKey(settings) })
117
- }
118
- }
119
-
120
- if (options.dryRun) out.write(`${profile}:删掉\n没有写入(--dry-run)\n`)
121
- else if (await removeProfile('gemini', env)) out.write(`已删掉 ${profile}\n`)
122
- else out.write(`${profile} 本来就没有\n`)
123
- return 0
124
- }
125
-
126
- await preflightGemini({ env })
127
- const { url, key, saved } = await resolveTarget({ id: 'gemini', name: 'Gemini CLI' }, options, {
128
- ...io,
129
- beforeLogin: () => preflightGemini({ env }),
130
- })
131
-
132
- const { settings, text } = await readSettings(file)
133
- checkStructure(settings, file)
134
- const next = buildSettings(settings, { url, key, undo: false })
135
- const sameProfile = Boolean(saved && saved.url === url && saved.key === key)
136
- const sameFile = JSON.stringify(settings) === JSON.stringify(next)
137
-
138
- if (sameProfile) out.write(`${profile} 不用改\n`)
139
- else out.write(`${profile}:写入服务地址与访问密钥(只给本人读写)\n`)
140
-
141
- if (sameFile) out.write(`${file} 不用改\n`)
142
- else out.write(`${file}:配置 mcpServers.kioku,停用自带 save_memory\n`)
143
-
144
- if (options.dryRun) {
145
- out.write('没有写入(--dry-run)\n')
146
- return 0
147
- }
148
-
149
- if (!sameProfile) await writeProfile('gemini', { url, key }, env)
150
- if (!sameFile) {
151
- const backedUp = await safeWrite(file, serialize(next, text), text, {
152
- backup: !hasStoredKey(settings),
153
- })
154
- if (backedUp) out.write(`原配置已备份到 ${file}.kioku-backup\n`)
155
- }
156
- out.write('Gemini CLI 已配好,重启 Gemini CLI 后生效。\n')
157
- if (!(await extensionInstalled(env, cwd)) && io.hints !== false) {
158
- out.write(
159
- '接下来链接扩展以启用生命周期钩子:gemini extensions link <仓库目录>/plugins/gemini\n',
160
- )
161
- }
162
- return 0
163
- }
164
-
165
- export async function inspectGemini({ env, cwd }, { ok, warn }) {
166
- const profile = await readProfile('gemini', env).catch(() => null)
167
- if (!profile) {
168
- warn('没有 kioku setup gemini 写下的地址与访问密钥,扩展钩子不会生效:运行 kioku setup gemini')
169
- }
170
-
171
- const file = geminiSettingsFile(env)
172
- const { settings } = await readSettings(file)
173
- const entry = settings?.mcpServers?.kioku
174
- if (!entry) {
175
- warn(`${file} 里没有 mcpServers.kioku:运行 kioku setup gemini`)
176
- } else if (!entry.httpUrl) {
177
- warn(`${file} 里的 mcpServers.kioku 缺少 httpUrl:运行 kioku setup gemini`)
178
- } else if (profile && !sameMcp(entry, mcpEntry(profile.url, profile.key))) {
179
- warn(`${file} 里的 mcpServers.kioku 与当前地址或访问密钥不一致:运行 kioku setup gemini`)
180
- } else {
181
- ok(`${file} 里的 mcpServers.kioku 已配好`)
182
- }
183
-
184
- if (Array.isArray(settings?.excludeTools) && settings.excludeTools.includes('save_memory')) {
185
- ok('Gemini CLI 自带的 save_memory 已停用(excludeTools)')
186
- } else {
187
- warn('Gemini CLI 自带的 save_memory 还开着:运行 kioku setup gemini 停用它')
188
- }
189
-
190
- if (await extensionInstalled(env, cwd)) ok('Gemini CLI 已安装 kioku 扩展')
191
- else warn('Gemini CLI 未安装 kioku 扩展:运行 gemini extensions link <仓库目录>/plugins/gemini')
192
- }
193
-
194
- export async function statusGemini({ env, cwd }) {
195
- const plugin = await extensionInstalled(env, cwd)
196
- const { settings } = await readSettings(geminiSettingsFile(env)).catch(() => ({}))
197
- const off = Array.isArray(settings?.excludeTools) && settings.excludeTools.includes('save_memory')
198
- return { plugin, memory: off ? 'off' : 'on' }
199
- }