@kioku-memory/openclaw 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.
package/lib/wizard.mjs DELETED
@@ -1,534 +0,0 @@
1
- // 在终端里不带参数运行 kioku 时的向导:一个状态面板,不是一条直线。先扫描服务器与本机各平台的现状,
2
- // 再按缺什么列出动作;每个动作先列计划、确认后执行,做完回到面板刷新。
3
- // 交互(选择、确认、输入)经 ui 这一层,接口照 @clack/prompts,用例里换成假的;
4
- // 各动作的实际步骤都是别的子命令已有的那一套(setup、login、import、doctor)
5
-
6
- import { loadConfig } from './config.mjs'
7
- import { conflictToolsText, formatConflicts, removeConflicts } from './conflicts.mjs'
8
- import { connectPlatforms, pluginSteps, resultsText } from './connect.mjs'
9
- import { doctor } from './doctor.mjs'
10
- import { keyFormatError, KiokuFailure } from './http.mjs'
11
- import { pendingOf, planImport, writeImport } from './import.mjs'
12
- import {
13
- composeState,
14
- composeUp,
15
- defaultLocalDir,
16
- expandDir,
17
- hasCompose,
18
- healthy,
19
- latestRelease,
20
- LOCAL_PORT,
21
- LOCAL_URL,
22
- manualDownload,
23
- portBusy,
24
- prepareDir,
25
- setupCodeIn,
26
- setupDone,
27
- waitUntil,
28
- } from './local.mjs'
29
- import { openBrowser } from './login.mjs'
30
- import {
31
- actionsFor,
32
- canDisable,
33
- connectCandidates,
34
- defaultServerUrl,
35
- renderPanel,
36
- scan,
37
- serverHealth,
38
- } from './panel.mjs'
39
- import { PLATFORMS } from './platforms.mjs'
40
- import { serverUrlProblem } from './profile.mjs'
41
- import { setup } from './setup.mjs'
42
- import { shownUrl } from './text.mjs'
43
-
44
- // 收下一段输出,给计划预览用
45
- export function bufferOut() {
46
- let text = ''
47
- return {
48
- write(chunk) {
49
- text += chunk
50
- return true
51
- },
52
- text: () => text.replace(/\n+$/, ''),
53
- }
54
- }
55
-
56
- // 接在向导的竖线下面写:每行前面加「│ 」,和 @clack/prompts 的排版对齐
57
- export function barOut(stream) {
58
- let atLineStart = true
59
- return {
60
- write(chunk) {
61
- let text = ''
62
- for (const char of String(chunk)) {
63
- if (atLineStart) text += char === '\n' ? '│' : '│ '
64
- text += char
65
- atLineStart = char === '\n'
66
- }
67
- return stream.write(text)
68
- },
69
- }
70
- }
71
-
72
- // 每个动作的默认依赖,用例里换成假的
73
- const DEPS = {
74
- scan,
75
- serverHealth,
76
- defaultServerUrl,
77
- connectPlatforms,
78
- pluginSteps,
79
- setup,
80
- doctor,
81
- planImport,
82
- writeImport,
83
- removeConflicts,
84
- loadConfig,
85
- open: openBrowser,
86
- local: {
87
- composeState,
88
- composeUp,
89
- hasCompose,
90
- healthy,
91
- latestRelease,
92
- portBusy,
93
- prepareDir,
94
- setupCodeIn,
95
- setupDone,
96
- waitUntil,
97
- },
98
- }
99
-
100
- const cancelled = (ui, value) => ui.isCancel(value)
101
-
102
- async function chooseServer(ctx) {
103
- const { ui, deps } = ctx
104
- const value = await ui.text({
105
- message: 'Kioku 的服务地址',
106
- placeholder: 'https://kioku.example.com',
107
- ...(ctx.url ? { initialValue: ctx.url } : {}),
108
- validate: (text) => serverUrlProblem((text ?? '').trim().replace(/\/+$/, '')) ?? undefined,
109
- })
110
- if (cancelled(ui, value)) return
111
- const url = value.trim().replace(/\/+$/, '')
112
- const health = await deps.serverHealth(url)
113
- if (!health.reachable) {
114
- const keep = await ui.confirm({
115
- message: `${shownUrl(url)} 无法连接(${health.problem}),仍然用这个地址?`,
116
- initialValue: false,
117
- })
118
- if (cancelled(ui, keep) || !keep) return
119
- }
120
- ctx.url = url
121
- }
122
-
123
- // 接入(或重新授权)几个平台:浏览器确认一次,签发的访问密钥照 kioku setup 写下
124
- async function connect(ctx, rows, { reauth = false } = {}) {
125
- const { ui, deps, env, cwd, out } = ctx
126
- if (!rows.length) return
127
- const picked = await ui.multiselect({
128
- message: reauth ? '重新授权哪些平台' : '接入哪些平台',
129
- options: rows.map((row) => ({
130
- value: row.id,
131
- label: row.name,
132
- ...(row.present ? {} : { hint: '本机没发现' }),
133
- })),
134
- initialValues: rows.filter((row) => reauth || row.present).map((row) => row.id),
135
- })
136
- if (cancelled(ui, picked) || !picked.length) return
137
- const plan = picked.map((id) => {
138
- const row = rows.find((item) => item.id === id)
139
- const memory = row.memory === 'none' ? '' : ',停用自带的长期记忆'
140
- const conflicts = row.conflicts?.filter((c) => c.removable) ?? []
141
- const clean = conflicts.length ? `,先清理 ${conflictToolsText(conflicts)}` : ''
142
- const moved = row.otherServer ? `;原来接到 ${shownUrl(row.url)}` : ''
143
- return `${PLATFORMS[id].name}:签发访问密钥,写下配置${memory}${clean}${moved}`
144
- })
145
- ui.note(
146
- [`服务器 ${shownUrl(ctx.url)}`, ...plan, '', '浏览器里确认一次,访问密钥不显示'].join('\n'),
147
- '计划',
148
- )
149
- const ok = await ui.confirm({ message: '开始?' })
150
- if (cancelled(ui, ok) || !ok) return
151
-
152
- const readyIds = []
153
- const preFailed = []
154
- for (const id of picked) {
155
- const row = rows.find((item) => item.id === id)
156
- const conflicts = row.conflicts?.filter((c) => c.removable) ?? []
157
- if (!conflicts.length) {
158
- readyIds.push(id)
159
- continue
160
- }
161
- const cleanRes = await deps.removeConflicts(conflicts, { env, cwd, out })
162
- if (cleanRes.some((r) => !r.ok)) {
163
- preFailed.push({ id, status: 'failed', reason: '清理冲突没有全部成功' })
164
- } else {
165
- readyIds.push(id)
166
- }
167
- }
168
- const results = readyIds.length
169
- ? await deps.connectPlatforms({ url: ctx.url, ids: readyIds }, { env, out, cwd })
170
- : []
171
- const allResults = [...preFailed, ...results]
172
- const done = allResults.filter((item) => item.status === 'connected').map((item) => item.id)
173
- ui.note(
174
- done.length ? resultsText(allResults) : `一个平台都没有接上\n${resultsText(allResults)}`,
175
- '结果',
176
- )
177
- const steps = await deps.pluginSteps(done, { env, cwd })
178
- if (steps) ui.note(steps, '装插件')
179
- }
180
-
181
- // 接入 Claude Code:它的访问密钥只认 /plugin 里填的,浏览器授权不给它发。列出安装命令与要填的服务地址,
182
- // 顺带停用自动记忆(项目设置又启用了的,说明要在那里改)
183
- async function connectClaude(ctx, row) {
184
- const { ui, deps, env, cwd, out } = ctx
185
- const steps = await deps.pluginSteps(['claude-code'], { env, cwd, url: ctx.url })
186
- const memory = row.memory === 'on' && !row.reenabledIn
187
- const conflicts = row.conflicts?.filter((c) => c.removable) ?? []
188
- if (row.reenabledIn) {
189
- ui.log.warn(
190
- `Claude Code 的自动记忆被 ./${row.reenabledIn} 重新启用:要在那里把 autoMemoryEnabled 去掉`,
191
- )
192
- }
193
- if (memory || conflicts.length) {
194
- const preview = bufferOut()
195
- if (memory) {
196
- await deps.setup(['claude-code', '--dry-run'], {
197
- env,
198
- out: preview,
199
- cwd,
200
- login: null,
201
- skipConflicts: true,
202
- })
203
- }
204
- const lines = []
205
- if (conflicts.length) {
206
- lines.push('清理冲突的记忆工具', ...formatConflicts(conflicts, PLATFORMS), '')
207
- }
208
- if (memory) {
209
- lines.push('停用自动记忆', preview.text().replace(/\n?没有写入(--dry-run)$/, ''), '')
210
- }
211
- lines.push(
212
- '插件与访问密钥在 Claude Code 的 /plugin 里装、填(浏览器授权不给它发访问密钥),做完列出步骤',
213
- )
214
- ui.note(lines.join('\n'), '计划')
215
- const ok = await ui.confirm({ message: '开始?' })
216
- if (cancelled(ui, ok) || !ok) return
217
- if (conflicts.length) {
218
- const cleanRes = await deps.removeConflicts(conflicts, { env, cwd, out })
219
- if (cleanRes.some((r) => !r.ok)) {
220
- throw new KiokuFailure('清理 Claude Code 上的冲突没有全部成功,已停下')
221
- }
222
- }
223
- if (memory) {
224
- await deps.setup(['claude-code'], {
225
- env,
226
- out: ctx.out,
227
- cwd,
228
- login: null,
229
- skipConflicts: true,
230
- })
231
- }
232
- }
233
- if (steps) ui.note(steps, '装插件')
234
- }
235
-
236
- // 先用 --dry-run 看要改什么,确认后再做
237
- async function previewThenRun(ctx, args, question) {
238
- const { ui, deps, env, cwd } = ctx
239
- const preview = bufferOut()
240
- await deps.setup([...args, '--dry-run'], {
241
- env,
242
- out: preview,
243
- cwd,
244
- login: null,
245
- skipConflicts: true,
246
- })
247
- ui.note(preview.text().replace(/\n?没有写入(--dry-run)$/, ''), '计划')
248
- const ok = await ui.confirm({ message: question })
249
- if (cancelled(ui, ok) || !ok) return
250
- await deps.setup(args, { env, out: ctx.out, cwd, login: null, skipConflicts: true })
251
- }
252
-
253
- // 迁移一个平台的本地记忆:照 kioku import 列计划(这时才和 Kioku 逐条比对)、确认后写入。
254
- // 比出来的未迁移条数记在这次向导里,面板上显示;写入之后作废
255
- async function migrate(ctx, id) {
256
- const { ui, deps, env, out } = ctx
257
- const platform = PLATFORMS[id]
258
- let config
259
- if (platform.readConfig) config = await platform.readConfig(env)
260
- else {
261
- // Claude Code 的访问密钥在它的 /plugin 里,读不到:Claude Code 的会话里有环境变量,否则请用户输入
262
- config = await deps.loadConfig(env).catch(() => null)
263
- if (!config || config.url !== ctx.url) {
264
- const key = await ui.password({
265
- message: `${platform.name} 用的访问密钥(记忆迁进它所属的应用)`,
266
- validate: (text) => keyFormatError((text ?? '').trim()) ?? undefined,
267
- })
268
- if (cancelled(ui, key)) return
269
- config = { url: ctx.url, key: key.trim() }
270
- }
271
- }
272
- if (!config) throw new KiokuFailure(`还没有给 ${platform.name} 配过:先接入`)
273
- const plan = await deps.planImport(config, { from: platform.source }, { env, out })
274
- if (plan.empty) {
275
- ctx.pending.set(id, { pending: 0 })
276
- return
277
- }
278
- ctx.pending.set(id, pendingOf(plan))
279
- if (!plan.todo.length) {
280
- ui.log.info('没有要写的')
281
- return
282
- }
283
- const ok = await ui.confirm({ message: `写入这 ${plan.todo.length} 条?` })
284
- if (cancelled(ui, ok) || !ok) return
285
- ctx.pending.delete(id)
286
- await deps.writeImport(config, plan, { out })
287
- }
288
-
289
- async function cleanConflictsAction(ctx, state) {
290
- const { ui, deps, env, cwd, out } = ctx
291
- const rows = state.platforms.filter((row) => row.conflicts?.some((c) => c.removable))
292
- if (!rows.length) return
293
- let ids = rows.map((row) => row.id)
294
- if (rows.length > 1) {
295
- const picked = await ui.multiselect({
296
- message: '清理哪些平台上的冲突记忆工具',
297
- options: rows.map((row) => ({
298
- value: row.id,
299
- label: row.name,
300
- hint: conflictToolsText(row.conflicts.filter((c) => c.removable)),
301
- })),
302
- initialValues: ids,
303
- })
304
- if (cancelled(ui, picked) || !picked.length) return
305
- ids = picked
306
- }
307
- const items = rows
308
- .filter((row) => ids.includes(row.id))
309
- .flatMap((row) => row.conflicts.filter((c) => c.removable))
310
- ui.note(formatConflicts(items, PLATFORMS).join('\n'), '计划')
311
- const ok = await ui.confirm({ message: `清理这 ${items.length} 项冲突?` })
312
- if (cancelled(ui, ok) || !ok) return
313
- const results = await deps.removeConflicts(items, { env, cwd, out })
314
- if (results.some((r) => !r.ok)) {
315
- throw new KiokuFailure('部分冲突没有清理成功,请查看上面的输出')
316
- }
317
- ui.log.success('冲突已清理,重启对应平台后生效')
318
- }
319
-
320
- async function disable(ctx, state) {
321
- const { ui } = ctx
322
- const rows = state.platforms.filter(canDisable)
323
- const id = await ui.select({
324
- message: '停用哪个平台(恢复自带记忆、清掉配置)',
325
- options: rows.map((row) => ({ value: row.id, label: row.name })),
326
- })
327
- if (cancelled(ui, id)) return
328
- await previewThenRun(ctx, [id, '--undo'], `停用 ${PLATFORMS[id].name}?`)
329
- }
330
-
331
- async function check(ctx) {
332
- const { ui, deps, env, cwd, out } = ctx
333
- const id = await ui.select({
334
- message: '检查哪个平台',
335
- options: Object.entries(PLATFORMS).map(([value, platform]) => ({
336
- value,
337
- label: platform.name,
338
- })),
339
- })
340
- if (cancelled(ui, id)) return
341
- await deps.doctor([id], { env, out, cwd })
342
- }
343
-
344
- // 打开管理界面,等第一个管理员建好
345
- async function awaitSetup(ctx, url, code) {
346
- const { ui, deps } = ctx
347
- if (code) ui.note(`初始化码:${code}\n在 ${url} 输入它,建第一个管理员`, '初始化')
348
- deps.open(url)
349
- const spin = ui.spinner()
350
- spin.start(`等待在 ${url} 建好管理员(Ctrl-C 退出)`)
351
- const done = await deps.local.waitUntil(() => deps.local.setupDone(url), {
352
- timeoutMs: 60 * 60_000,
353
- intervalMs: 3000,
354
- })
355
- spin.stop(done ? '管理员已建好' : '没有等到初始化完成')
356
- return done
357
- }
358
-
359
- // 等这个目录里的 Kioku 就绪
360
- async function waitHealthy(ctx, dir, spin) {
361
- spin.message?.('等待 Kioku 就绪')
362
- const up = await ctx.deps.local.waitUntil(() => ctx.deps.local.healthy(LOCAL_URL), {
363
- timeoutMs: 180_000,
364
- })
365
- spin.stop(up ? 'Kioku 已就绪' : 'Kioku 没有就绪')
366
- if (!up) {
367
- throw new KiokuFailure(
368
- `Kioku 在 3 分钟内没有就绪:运行 cd ${dir} && docker compose logs kioku 看原因`,
369
- )
370
- }
371
- }
372
-
373
- // docker compose up -d,等它就绪
374
- async function bringUp(ctx, dir) {
375
- const spin = ctx.ui.spinner()
376
- spin.start('docker compose up -d(第一次要拉镜像,可能要几分钟)')
377
- try {
378
- await ctx.deps.local.composeUp(dir, ctx.env)
379
- } catch (err) {
380
- spin.stop('没有起来')
381
- throw err
382
- }
383
- await waitHealthy(ctx, dir, spin)
384
- }
385
-
386
- // 本机起一个 Kioku:放好 compose.yaml 与 .env,docker compose up -d,等它就绪、等用户建好管理员。
387
- // 目录里已经有这个 compose 项目(上次起过)时不再判端口、不重新准备,接着启动或等它就绪
388
- async function startLocal(ctx) {
389
- const { ui, deps, env } = ctx
390
- const local = deps.local
391
- if (await local.healthy(LOCAL_URL)) {
392
- ui.log.info(`本机 ${LOCAL_PORT} 端口上已经有 Kioku 在运行,直接用它`)
393
- ctx.url = LOCAL_URL
394
- return
395
- }
396
- if (!(await local.hasCompose(env))) {
397
- throw new KiokuFailure('没有找到 docker compose:先装好 Docker(含 compose 插件)再来')
398
- }
399
- const answer = await ui.text({
400
- message: '放在哪个目录',
401
- initialValue: defaultLocalDir(env),
402
- validate: (text) => ((text ?? '').trim() ? undefined : '要写目录'),
403
- })
404
- if (cancelled(ui, answer)) return
405
- const dir = expandDir(answer.trim(), env)
406
-
407
- const existing = await local.composeState(dir, env)
408
- let code
409
- if (existing === 'running') {
410
- ui.log.info(`${dir} 里的 Kioku 已经在运行,等它就绪`)
411
- const spin = ui.spinner()
412
- spin.start('等待 Kioku 就绪')
413
- await waitHealthy(ctx, dir, spin)
414
- code = await local.setupCodeIn(dir)
415
- } else if (existing === 'stopped') {
416
- ui.note(`目录 ${dir}\n这里的 Kioku 建过、没在运行:docker compose up -d`, '计划')
417
- const ok = await ui.confirm({ message: '启动?' })
418
- if (cancelled(ui, ok) || !ok) return
419
- await bringUp(ctx, dir)
420
- code = await local.setupCodeIn(dir)
421
- } else {
422
- if (await local.portBusy(LOCAL_PORT)) {
423
- throw new KiokuFailure(
424
- `端口 ${LOCAL_PORT} 被别的程序占着:先停掉它(lsof -i :${LOCAL_PORT} 看是哪个),或者改 compose.yaml 里的端口后自己启动`,
425
- )
426
- }
427
- const release = await local.latestRelease()
428
- if (!release.release) {
429
- ui.log.warn(
430
- `没取到最新的正式版(${release.problem}):用 main 上的 compose.yaml 与 edge 镜像(main 上最新的提交,不保证稳定)`,
431
- )
432
- }
433
- ui.note(
434
- [
435
- `目录 ${dir}`,
436
- `版本 ${release.imageTag}${release.release ? '(最新的正式版)' : ''}`,
437
- `下载 ${release.ref} 的 compose.yaml、.env.example(已有的不覆盖)`,
438
- `生成 .env:数据库密码、主密钥、初始化码随机生成,镜像固定在 ${release.imageTag},只给本人读写(已有的不覆盖)`,
439
- `docker compose up -d,端口只开在 127.0.0.1:${LOCAL_PORT}`,
440
- ].join('\n'),
441
- '计划',
442
- )
443
- const ok = await ui.confirm({ message: '开始?' })
444
- if (cancelled(ui, ok) || !ok) return
445
-
446
- let prepared
447
- try {
448
- prepared = await local.prepareDir(dir, release)
449
- } catch (err) {
450
- if (!(err instanceof KiokuFailure)) throw err
451
- ui.note(manualDownload(dir, release.ref), '手动下载')
452
- throw err
453
- }
454
- if (prepared.env.written) {
455
- ui.log.warn(
456
- `主密钥在 ${prepared.env.file} 的 KIOKU_MASTER_KEY:另外保存一份,和数据库备份分开放;丢了机密记忆与托管凭据解不开`,
457
- )
458
- } else ui.log.info(`${prepared.env.file} 已经有了,沿用`)
459
- await bringUp(ctx, dir)
460
- code = prepared.env.setupCode
461
- }
462
- ctx.url = LOCAL_URL
463
- if (await local.setupDone(LOCAL_URL)) return 'connect'
464
- if (!code) ui.log.info(`初始化码看日志:cd ${dir} && docker compose logs kioku`)
465
- if (await awaitSetup(ctx, LOCAL_URL, code)) return 'connect'
466
- }
467
-
468
- async function perform(ctx, choice, state) {
469
- if (choice === 'server') return chooseServer(ctx)
470
- if (choice === 'local') {
471
- if ((await startLocal(ctx)) === 'connect') {
472
- const next = await ctx.deps.scan({ env: ctx.env, cwd: ctx.cwd, url: ctx.url })
473
- return connect(ctx, connectCandidates(next))
474
- }
475
- return
476
- }
477
- if (choice === 'open') {
478
- await awaitSetup(ctx, ctx.url, null)
479
- return
480
- }
481
- if (choice === 'connect') return connect(ctx, connectCandidates(state))
482
- if (choice === 'reauth') {
483
- return connect(
484
- ctx,
485
- state.platforms.filter((row) => row.connection === 'invalid'),
486
- { reauth: true },
487
- )
488
- }
489
- if (choice === 'claude-connect') {
490
- return connectClaude(
491
- ctx,
492
- state.platforms.find((row) => row.id === 'claude-code'),
493
- )
494
- }
495
- if (choice === 'claude-memory') {
496
- return previewThenRun(ctx, ['claude-code'], '停用 Claude Code 的自动记忆?')
497
- }
498
- if (choice.startsWith('import:')) return migrate(ctx, choice.slice('import:'.length))
499
- if (choice === 'clean') return cleanConflictsAction(ctx, state)
500
- if (choice === 'disable') return disable(ctx, state)
501
- if (choice === 'doctor') return check(ctx)
502
- }
503
-
504
- // 向导的主循环,返回退出码
505
- export async function wizard({ ui, env, cwd, out, deps = {} }) {
506
- // pending:选过迁移的平台比出来的未迁移条数(平台 id → pendingOf 的结果),只在这次向导里有效
507
- const ctx = { ui, env, cwd, out, deps: { ...DEPS, ...deps }, url: null, pending: new Map() }
508
- ctx.url = await ctx.deps.defaultServerUrl(env)
509
- ui.intro('Kioku')
510
- for (;;) {
511
- const spin = ui.spinner()
512
- spin.start('读取现状')
513
- const state = await ctx.deps.scan({ env, cwd, url: ctx.url })
514
- for (const row of state.platforms) {
515
- if (ctx.pending.has(row.id)) row.pending = ctx.pending.get(row.id)
516
- }
517
- spin.stop('现状')
518
- ui.note(renderPanel(state), '面板')
519
- const choice = await ui.select({ message: '要做什么', options: actionsFor(state) })
520
- if (cancelled(ui, choice) || choice === 'exit') {
521
- ui.outro('再运行 kioku 回到这里')
522
- return 0
523
- }
524
- if (choice === 'refresh') continue
525
- // 换了服务器、接入或停用之后,比过的未迁移条数可能对不上了
526
- if (!choice.startsWith('import:') && choice !== 'doctor') ctx.pending.clear()
527
- try {
528
- await perform(ctx, choice, state)
529
- } catch (err) {
530
- if (!(err instanceof KiokuFailure)) throw err
531
- ui.log.error(err.message)
532
- }
533
- }
534
- }