@kioku-memory/openclaw 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,152 @@
1
+ // 把几个平台接到 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 CHANGED
@@ -3,6 +3,7 @@
3
3
 
4
4
  import { loadConfig, NotConfigured } from './config.mjs'
5
5
  import { whoami } from './api.mjs'
6
+ import { scanConflicts } from './conflicts.mjs'
6
7
  import { failureText, KiokuFailure } from './http.mjs'
7
8
  import { detectPlatform, platformNames, PLATFORMS } from './platforms.mjs'
8
9
  import { readSettings } from './files.mjs'
@@ -108,12 +109,23 @@ export async function doctor(
108
109
  out.write(`没有认出平台,只查了地址与访问密钥;要查平台的配置,写上平台:${platformNames()}\n`)
109
110
  return failed ? 1 : 0
110
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
+
111
125
  if (platform.inspect) {
112
126
  try {
113
- await platform.inspect(
114
- { env, cwd },
115
- { ok, warn, bad, note: (text) => out.write(` ${text}\n`) },
116
- )
127
+ await platform.inspect({ env, cwd }, { ok, warn, bad, note })
128
+ await checkConflicts()
117
129
  } catch (err) {
118
130
  bad(failureText(err))
119
131
  }
@@ -141,5 +153,6 @@ export async function doctor(
141
153
  )
142
154
  }
143
155
  }
156
+ await checkConflicts()
144
157
  return failed ? 1 : 0
145
158
  }
package/lib/dsh.mjs CHANGED
@@ -59,7 +59,9 @@ export async function setupDsh(options, io) {
59
59
  const profiles = await installedProfiles(env)
60
60
  out.write('DeepSeek Harness 已配好,重启 dsh 后生效(读写记忆的工具在启动时连上)。\n')
61
61
  if (profiles.length) out.write(`装了插件的 profile:${profiles.map(plain).join('、')}\n`)
62
- else out.write(`接下来给要用的 profile 装上插件(web、tui 这些各装一次):${installHint}\n`)
62
+ else if (io.hints !== false) {
63
+ out.write(`接下来给要用的 profile 装上插件(web、tui 这些各装一次):${installHint}\n`)
64
+ }
63
65
  return 0
64
66
  }
65
67
 
@@ -73,3 +75,8 @@ export async function inspectDsh({ env }, { ok, warn, note }) {
73
75
  note('插件按 profile 装:没装的 profile 里没有长期记忆')
74
76
  ok('DeepSeek Harness 没有自带的长期记忆要停用')
75
77
  }
78
+
79
+ // 给向导的面板:有没有哪个 profile 装了插件,dsh 没有自带的长期记忆
80
+ export async function statusDsh({ env }) {
81
+ return { plugin: (await installedProfiles(env)).length > 0, memory: 'none' }
82
+ }
package/lib/gemini.mjs ADDED
@@ -0,0 +1,199 @@
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
+ }
package/lib/hermes.mjs CHANGED
@@ -59,7 +59,7 @@ export async function readHermesConfig(env) {
59
59
 
60
60
  // 把这几项写进 .env 的全文:同名的行只留一处(换成新值),没有的加在最后;values 里为 null 的全都去掉。
61
61
  // 别的行不动;没有要改的时候原样返回,不顺手整理空行与换行符
62
- function withEnv(text, values) {
62
+ export function withEnv(text, values) {
63
63
  const eol = text?.includes('\r\n') ? '\r\n' : '\n'
64
64
  const written = new Set()
65
65
  let touched = false
@@ -219,7 +219,7 @@ export async function setupHermes(options, io) {
219
219
  out.write('地址与访问密钥已经写下。\n')
220
220
  manual(out, SETTINGS, state)
221
221
  }
222
- if (!(await installed(env))) {
222
+ if (!(await installed(env)) && io.hints !== false) {
223
223
  out.write(`接下来装上 provider:hermes plugins install ${SOURCE} --enable\n`)
224
224
  }
225
225
  return 0
@@ -259,3 +259,18 @@ export async function inspectHermes({ env }, { ok, warn, note }) {
259
259
  } else ok('Hermes 内置的记忆文件已停用')
260
260
  note('只在本机的会话里生效;消息网关来的会话里不注入、不上报、不给工具')
261
261
  }
262
+
263
+ // 给向导的面板:provider 装没装;自带的记忆停没停(选的是 kioku、内置的两份都关了才算停了;
264
+ // 没有 hermes 命令、命令失败时为 null)
265
+ export async function statusHermes({ env }) {
266
+ const plugin = await installed(env)
267
+ const provider = await configValue(env, 'memory.provider')
268
+ if (provider === null || provider === undefined) return { plugin, memory: null }
269
+ const flags = [
270
+ await configValue(env, 'memory.memory_enabled'),
271
+ await configValue(env, 'memory.user_profile_enabled'),
272
+ ]
273
+ if (flags.some((value) => value === null || value === undefined)) return { plugin, memory: null }
274
+ const off = provider === 'kioku' && flags.every((value) => !/^true$/i.test(value))
275
+ return { plugin, memory: off ? 'off' : 'on' }
276
+ }
package/lib/import.mjs CHANGED
@@ -135,7 +135,7 @@ async function write(config, item) {
135
135
  const KINDS = { new: '新建', same: '已有,内容一样', differs: '已有,内容不一样' }
136
136
 
137
137
  // 问一句是或否;只认 y 开头的回答
138
- async function confirm(question, { stdin, out }) {
138
+ export async function confirm(question, { stdin, out }) {
139
139
  out.write(question)
140
140
  for await (const chunk of stdin) {
141
141
  return /^\s*y/i.test(chunk.toString('utf8'))
@@ -143,38 +143,53 @@ async function confirm(question, { stdin, out }) {
143
143
  return false
144
144
  }
145
145
 
146
- export async function importMemories(
147
- argv,
148
- { env = process.env, out = process.stdout, stdin = process.stdin } = {},
149
- ) {
150
- const options = parseImportArgs(argv)
151
- const source = SOURCES[options.from]
152
- // 地址与访问密钥:指明了平台就用 kioku setup 给它写下的,否则读环境变量
153
- let config
154
- if (options.platform) {
155
- config = await PLATFORMS[options.platform].readConfig(env)
156
- if (!config) {
157
- throw new KiokuFailure(
158
- `还没有给 ${options.platform} 配过:先运行 kioku setup ${options.platform}`,
159
- )
146
+ // 本地的这个来源里有几条能迁的记忆(不和 Kioku 比)。来源的目录不在时为 null
147
+ export async function countLocal(from, { env, path }) {
148
+ const { found, entries } = await SOURCES[from].read({ env, path, app: 'app' })
149
+ return found ? entries.filter((item) => !item.skipped).length : null
150
+ }
151
+
152
+ // 按顺序对每一项做 fn,同时最多 limit 个;结果的顺序和 items 一样
153
+ async function mapLimit(items, limit, fn) {
154
+ const results = new Array(items.length)
155
+ let next = 0
156
+ const worker = async () => {
157
+ while (next < items.length) {
158
+ const index = next++
159
+ results[index] = await fn(items[index])
160
160
  }
161
- } else config = await loadConfig(env)
161
+ }
162
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker))
163
+ return results
164
+ }
165
+
166
+ // 和 Kioku 里比时同时发的请求数
167
+ const COMPARE_CONCURRENCY = 8
168
+
169
+ // 计划里还没迁进 Kioku 的条数(Kioku 里同一个坐标还没有的)。有比对失败的(不是 200、404)时
170
+ // 说不准,pending 为 null,reason 写明几条读取失败
171
+ export function pendingOf(plan) {
172
+ const failed = plan.compared.filter((item) => item.state === 'failed').length
173
+ if (failed) return { pending: null, reason: `${failed} 条读取失败` }
174
+ return { pending: plan.compared.filter((item) => item.state === 'new').length }
175
+ }
176
+
177
+ // 读本地的记忆、和 Kioku 里的比过,列出计划:每条放到哪个坐标、Kioku 里有没有。
178
+ // 返回 { compared, skipped, todo };没有可以迁的时 todo 是空的、empty 为真
179
+ export async function planImport(config, { from, path, overwrite = false }, { env, out }) {
180
+ const source = SOURCES[from]
162
181
  const who = await whoami(config)
163
182
  out.write(
164
183
  `Kioku:${shownUrl(config.url)},应用 ${plain(who.app.name)}(${plain(who.app.slug)})\n`,
165
184
  )
166
185
 
167
- const { root, found, entries } = await source.read({
168
- env,
169
- path: options.path,
170
- app: who.app.slug,
171
- })
186
+ const { root, found, entries } = await source.read({ env, path, app: who.app.slug })
172
187
  if (!found)
173
188
  throw new KiokuFailure(`没有找到${source.name}:${plain(root)} 不是目录,用 --path 指明位置`)
174
189
  out.write(`来源:${source.name}(${plain(root)})\n`)
175
190
  if (!entries.length) {
176
191
  out.write('没有可以迁的记忆\n')
177
- return 0
192
+ return { compared: [], skipped: [], todo: [], empty: true }
178
193
  }
179
194
 
180
195
  // 两条落到同一个坐标的(名字规整之后撞了)只留第一条
@@ -190,8 +205,8 @@ export async function importMemories(
190
205
  usable.push(item)
191
206
  }
192
207
  }
193
- const compared = []
194
- for (const item of usable) compared.push(await compare(config, item))
208
+ // 一条一个请求:有界并发,几百条也不至于等太久
209
+ const compared = await mapLimit(usable, COMPARE_CONCURRENCY, (item) => compare(config, item))
195
210
 
196
211
  out.write('\n')
197
212
  for (const item of compared) {
@@ -202,29 +217,17 @@ export async function importMemories(
202
217
 
203
218
  const count = (state) => compared.filter((item) => item.state === state).length
204
219
  const todo = compared.filter(
205
- (item) => item.state === 'new' || (item.state === 'differs' && options.overwrite),
220
+ (item) => item.state === 'new' || (item.state === 'differs' && overwrite),
206
221
  )
207
222
  out.write(
208
223
  `\n新建 ${count('new')} 条,已有且一样 ${count('same')} 条,已有但不一样 ${count('differs')} 条` +
209
- `(${options.overwrite ? '覆盖' : '跳过,要覆盖加 --overwrite'}),不迁 ${skipped.length} 条\n`,
224
+ `(${overwrite ? '覆盖' : '跳过,要覆盖加 --overwrite'}),不迁 ${skipped.length} 条\n`,
210
225
  )
211
- if (options.dryRun) {
212
- out.write('没有写入(--dry-run)\n')
213
- return 0
214
- }
215
- if (!todo.length) {
216
- out.write('没有要写的\n')
217
- return compared.some((item) => item.state === 'failed') ? 1 : 0
218
- }
219
- if (!options.yes) {
220
- if (!stdin.isTTY)
221
- throw new KiokuFailure('不在终端里运行时要带 --yes 才写;先用 --dry-run 看计划')
222
- if (!(await confirm(`写入这 ${todo.length} 条?[y/N] `, { stdin, out }))) {
223
- out.write('没有写入\n')
224
- return 0
225
- }
226
- }
226
+ return { compared, skipped, todo, empty: false }
227
+ }
227
228
 
229
+ // 按计划写入,返回退出码:有没写成的、读取失败的为 1
230
+ export async function writeImport(config, { compared, todo }, { out }) {
228
231
  let written = 0
229
232
  const failed = []
230
233
  // 连不上、超时这类不是某一条的问题:停下来,把已经写了多少、还剩多少说清楚,不让它跳出整个命令
@@ -260,3 +263,39 @@ export async function importMemories(
260
263
  out.write('本地的文件没有动。\n')
261
264
  return stopped || failed.length || compared.some((item) => item.state === 'failed') ? 1 : 0
262
265
  }
266
+
267
+ export async function importMemories(
268
+ argv,
269
+ { env = process.env, out = process.stdout, stdin = process.stdin } = {},
270
+ ) {
271
+ const options = parseImportArgs(argv)
272
+ // 地址与访问密钥:指明了平台就用 kioku setup 给它写下的,否则读环境变量
273
+ let config
274
+ if (options.platform) {
275
+ config = await PLATFORMS[options.platform].readConfig(env)
276
+ if (!config) {
277
+ throw new KiokuFailure(
278
+ `还没有给 ${options.platform} 配过:先运行 kioku setup ${options.platform}`,
279
+ )
280
+ }
281
+ } else config = await loadConfig(env)
282
+ const plan = await planImport(config, options, { env, out })
283
+ if (plan.empty) return 0
284
+ if (options.dryRun) {
285
+ out.write('没有写入(--dry-run)\n')
286
+ return 0
287
+ }
288
+ if (!plan.todo.length) {
289
+ out.write('没有要写的\n')
290
+ return plan.compared.some((item) => item.state === 'failed') ? 1 : 0
291
+ }
292
+ if (!options.yes) {
293
+ if (!stdin.isTTY)
294
+ throw new KiokuFailure('不在终端里运行时要带 --yes 才写;先用 --dry-run 看计划')
295
+ if (!(await confirm(`写入这 ${plan.todo.length} 条?[y/N] `, { stdin, out }))) {
296
+ out.write('没有写入\n')
297
+ return 0
298
+ }
299
+ }
300
+ return writeImport(config, plan, { out })
301
+ }