@kioku-memory/cli 0.3.0 → 0.4.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.
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/hermes.mjs DELETED
@@ -1,276 +0,0 @@
1
- // Hermes 这个平台的 kioku setup 与 kioku doctor。
2
- // Hermes 的记忆 provider 从这个 profile 的 .env 读 KIOKU_SERVER_URL 与 KIOKU_API_KEY,所以地址与访问密钥写在那里
3
- // (不另放一份);选 provider、关掉内置的两份记忆文件是 config.yaml 里的三项,交给 Hermes 自己的 hermes config set 去改,
4
- // 不自己动它的 YAML
5
-
6
- import { stat } from 'node:fs/promises'
7
- import { homedir } from 'node:os'
8
- import { join } from 'node:path'
9
-
10
- import { capture } from './command.mjs'
11
- import { readText, safeWrite } from './files.mjs'
12
- import { keyFormatError, KiokuFailure } from './http.mjs'
13
- import { serverUrlProblem } from './profile.mjs'
14
- import { resolveTarget } from './target.mjs'
15
-
16
- const SOURCE = 'lonelyman0108/kioku-plugins/plugins/hermes'
17
- // 要 Hermes 改的三项:选 Kioku,关掉内置的 MEMORY.md 与 USER.md(不关的话两边各记一份)
18
- const SETTINGS = [
19
- ['memory.provider', 'kioku'],
20
- ['memory.memory_enabled', 'false'],
21
- ['memory.user_profile_enabled', 'false'],
22
- ]
23
- const RESTORED = [
24
- ['memory.provider', ''],
25
- ['memory.memory_enabled', 'true'],
26
- ['memory.user_profile_enabled', 'true'],
27
- ]
28
- const URL_KEY = 'KIOKU_SERVER_URL'
29
- const API_KEY = 'KIOKU_API_KEY'
30
-
31
- export function hermesHome(env) {
32
- return env.HERMES_HOME || join(homedir(), '.hermes')
33
- }
34
-
35
- // .env 里的一行「名字=值」。值两边成对的引号去掉;没加引号的值后面的「 # 注释」不算值。不是这种行时为 null
36
- function envLine(line) {
37
- const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/.exec(line)
38
- if (!match) return null
39
- const quoted = /^(["'])(.*)\1(?:\s+#.*)?$/.exec(match[2])
40
- const value = quoted ? quoted[2] : match[2].replace(/\s+#.*$/, '')
41
- return { name: match[1], value }
42
- }
43
-
44
- // .env 里现在写的地址与访问密钥(同名的写了几行时以最后一行为准,和 Hermes 读它的方式一致);
45
- // 没有、不完整、格式不对时为 null
46
- export async function readHermesConfig(env) {
47
- const file = join(hermesHome(env), '.env')
48
- const text = await readText(file)
49
- const values = {}
50
- for (const line of (text ?? '').split(/\r?\n/)) {
51
- const pair = envLine(line)
52
- if (pair) values[pair.name] = pair.value
53
- }
54
- const url = (values[URL_KEY] ?? '').trim().replace(/\/+$/, '')
55
- const key = (values[API_KEY] ?? '').trim()
56
- if (!url || !key || serverUrlProblem(url) || keyFormatError(key)) return null
57
- return { url, key, file }
58
- }
59
-
60
- // 把这几项写进 .env 的全文:同名的行只留一处(换成新值),没有的加在最后;values 里为 null 的全都去掉。
61
- // 别的行不动;没有要改的时候原样返回,不顺手整理空行与换行符
62
- export function withEnv(text, values) {
63
- const eol = text?.includes('\r\n') ? '\r\n' : '\n'
64
- const written = new Set()
65
- let touched = false
66
- const lines = []
67
- for (const line of text ? text.split(/\r?\n/) : []) {
68
- const pair = envLine(line)
69
- if (!pair || !Object.hasOwn(values, pair.name)) {
70
- lines.push(line)
71
- continue
72
- }
73
- const wanted = values[pair.name]
74
- // 同名的第二行起、要去掉的:都不留(留着的话 Hermes 读到的是最后那一行的旧值)
75
- if (wanted === null || written.has(pair.name)) {
76
- touched = true
77
- continue
78
- }
79
- written.add(pair.name)
80
- const next = `${pair.name}=${wanted}`
81
- if (next !== line) touched = true
82
- lines.push(next)
83
- }
84
- const missing = Object.entries(values).filter(
85
- ([name, value]) => value !== null && !written.has(name),
86
- )
87
- if (!touched && !missing.length) return text ?? ''
88
- while (lines.length && lines.at(-1) === '') lines.pop()
89
- for (const [name, value] of missing) lines.push(`${name}=${value}`)
90
- return lines.length ? `${lines.join(eol)}${eol}` : ''
91
- }
92
-
93
- // 调 hermes 命令。找不到这个命令时返回 null;失败(含超时)时抛 KiokuFailure(不带输出:里面可能有别的配置)
94
- async function hermes(env, args) {
95
- const result = await capture(env.KIOKU_HERMES_BIN || 'hermes', args, env, { timeout: 30_000 })
96
- if (!result.found) return null
97
- if (!result.ok) throw new KiokuFailure(`hermes ${args.slice(0, 3).join(' ')} 没有成功`)
98
- return result.stdout
99
- }
100
-
101
- // 读 Hermes 的一项配置:null 是没有 hermes 命令,undefined 是没读出来(命令失败),否则是值(没设时是空字符串)
102
- async function configValue(env, key) {
103
- let out
104
- try {
105
- out = await hermes(env, ['config', 'get', key])
106
- } catch {
107
- return undefined
108
- }
109
- if (out === null) return null
110
- return out.trim().split(/\r?\n/).at(-1)?.trim() ?? ''
111
- }
112
-
113
- const sameValue = (a, b) => String(a).toLowerCase() === String(b).toLowerCase()
114
-
115
- // 逐项让 Hermes 改配置,改完读回来核对(托管的安装里 config set 不生效却照样成功退出)。
116
- // 返回 'done'、'no-hermes'(没有这个命令)或 'failed'(命令失败或没改成)。不抛错:
117
- // 调用方这时多半已经把访问密钥写下了,不能让这里的失败看起来像什么都没写
118
- async function applySettings(env, settings) {
119
- try {
120
- for (const [key, value] of settings) {
121
- if ((await hermes(env, ['config', 'set', key, value])) === null) return 'no-hermes'
122
- }
123
- for (const [key, value] of settings) {
124
- const now = await configValue(env, key)
125
- if (now === null || now === undefined || !sameValue(now, value)) return 'failed'
126
- }
127
- return 'done'
128
- } catch {
129
- return 'failed'
130
- }
131
- }
132
-
133
- function manual(out, settings, state) {
134
- out.write(
135
- state === 'no-hermes'
136
- ? '没有找到 hermes 命令,这几项要自己运行:\n'
137
- : 'Hermes 的配置没有改成(它的命令失败了,或者这份安装的配置是托管的),这几项要自己处理:\n',
138
- )
139
- for (const [key, value] of settings) out.write(` hermes config set ${key} ${value || '""'}\n`)
140
- }
141
-
142
- async function installed(env) {
143
- return Boolean(
144
- await stat(join(hermesHome(env), 'plugins', 'kioku', 'plugin.yaml')).catch(() => null),
145
- )
146
- }
147
-
148
- async function undo({ dryRun }, { env, out }) {
149
- const file = join(hermesHome(env), '.env')
150
- const text = await readText(file)
151
- const next = withEnv(text, { [URL_KEY]: null, [API_KEY]: null })
152
- const changed = text !== null && next !== text
153
- if (changed) out.write(`${file}\n ${URL_KEY}、${API_KEY}:去掉\n`)
154
- // 只在现在选的还是 kioku 时把配置改回去:之后换成了别的 provider 的话,不去动它
155
- const provider = await configValue(env, 'memory.provider')
156
- const ours = provider === 'kioku'
157
- if (ours) {
158
- out.write('Hermes 的配置\n')
159
- for (const [key, value] of RESTORED) out.write(` ${key} → ${value || '(内置的)'}\n`)
160
- } else if (provider === null) {
161
- out.write('没有找到 hermes 命令,Hermes 的配置没有动\n')
162
- } else {
163
- out.write('Hermes 现在选的记忆 provider 不是 kioku,它的配置没有动\n')
164
- }
165
- if (dryRun) {
166
- out.write('没有写入(--dry-run)\n')
167
- return 0
168
- }
169
- // .env 里有访问密钥与别的密钥,不留备份
170
- if (changed) await safeWrite(file, next, text, { backup: false })
171
- if (ours) {
172
- const state = await applySettings(env, RESTORED)
173
- if (state !== 'done') manual(out, RESTORED, state)
174
- else out.write('Hermes 改回用内置的记忆(两个开关都打开了;之前自己关过的要再关一次)。\n')
175
- }
176
- out.write('provider 要另外卸载:hermes plugins remove kioku\n')
177
- return 0
178
- }
179
-
180
- // kioku login 申请之前、setup 动手之前先看:Hermes 的目录在不在
181
- export async function preflightHermes({ env }) {
182
- const home = hermesHome(env)
183
- if (!(await stat(home).catch(() => null))?.isDirectory()) {
184
- throw new KiokuFailure(
185
- `没有找到 Hermes 的目录 ${home}:先装好并运行一次 Hermes,或者用 HERMES_HOME 指明`,
186
- )
187
- }
188
- }
189
-
190
- export async function setupHermes(options, io) {
191
- const { env, out } = io
192
- if (options.undo) return undo(options, io)
193
- const home = hermesHome(env)
194
- await preflightHermes({ env })
195
- const { url, key, saved } = await resolveTarget({ id: 'hermes', name: 'Hermes' }, options, {
196
- ...io,
197
- readSaved: () => readHermesConfig(env),
198
- })
199
- const file = join(home, '.env')
200
- const text = await readText(file)
201
- const next = withEnv(text, { [URL_KEY]: url, [API_KEY]: key })
202
- // 同名的行写了几处时,哪怕最后生效的值是对的也要收拾成一处
203
- const same = Boolean(saved && saved.url === url && saved.key === key) && next === (text ?? '')
204
- if (same) out.write(`${file} 不用改\n`)
205
- else out.write(`${file}\n ${URL_KEY}、${API_KEY}:写入\n`)
206
- out.write('Hermes 的配置\n')
207
- for (const [name, value] of SETTINGS) out.write(` ${name} → ${value}\n`)
208
- if (options.dryRun) {
209
- out.write('没有写入(--dry-run)\n')
210
- return 0
211
- }
212
- // .env 里有访问密钥与别的密钥,不留备份;新建的只给本人读写(safeWrite 的规矩)
213
- if (!same) await safeWrite(file, next, text, { backup: false })
214
- // 访问密钥这时已经写下了:后面改 Hermes 的配置不成也不算失败,把要做的列出来
215
- const state = await applySettings(env, SETTINGS)
216
- if (state === 'done') {
217
- out.write('Hermes 已配好,新开会话生效。内置的 MEMORY.md、USER.md 不再读写,文件还在。\n')
218
- } else {
219
- out.write('地址与访问密钥已经写下。\n')
220
- manual(out, SETTINGS, state)
221
- }
222
- if (!(await installed(env)) && io.hints !== false) {
223
- out.write(`接下来装上 provider:hermes plugins install ${SOURCE} --enable\n`)
224
- }
225
- return 0
226
- }
227
-
228
- export async function inspectHermes({ env }, { ok, warn, note }) {
229
- const home = hermesHome(env)
230
- if (!(await readHermesConfig(env))) {
231
- warn(
232
- `${join(home, '.env')} 里没有 Kioku 的地址与访问密钥,provider 不会生效:运行 kioku setup hermes`,
233
- )
234
- }
235
- if (await installed(env)) ok('Hermes 里装了 kioku 的记忆 provider')
236
- else warn(`Hermes 里没有装 kioku 的记忆 provider:hermes plugins install ${SOURCE} --enable`)
237
-
238
- const provider = await configValue(env, 'memory.provider')
239
- if (provider === null) {
240
- note('没有找到 hermes 命令,查不了它的配置:用 hermes memory status 看')
241
- return
242
- }
243
- const flags = [
244
- [await configValue(env, 'memory.memory_enabled'), 'MEMORY.md'],
245
- [await configValue(env, 'memory.user_profile_enabled'), 'USER.md'],
246
- ]
247
- // 没读出来的不下结论
248
- if (provider === undefined || flags.some(([value]) => value === undefined)) {
249
- warn('Hermes 的配置没有读出来(hermes config get 失败了):用 hermes memory status 看')
250
- return
251
- }
252
- if (provider === 'kioku') ok('Hermes 选的记忆 provider 是 kioku')
253
- else warn(`Hermes 现在选的记忆 provider 不是 kioku:运行 kioku setup hermes`)
254
- const builtin = flags.filter(([value]) => /^true$/i.test(value)).map(([, label]) => label)
255
- if (builtin.length) {
256
- warn(
257
- `Hermes 内置的 ${builtin.join('、')} 还开着,会和 Kioku 各记一份:运行 kioku setup hermes 关掉`,
258
- )
259
- } else ok('Hermes 内置的记忆文件已停用')
260
- note('只在本机的会话里生效;消息网关来的会话里不注入、不上报、不给工具')
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 DELETED
@@ -1,301 +0,0 @@
1
- // kioku import:把平台自带的本地长期记忆迁进 Kioku。先读本地文件出一份计划(每条放到哪个坐标),
2
- // 和 Kioku 里已有的比过之后列出来,确认了才写。坐标由来源决定,所以重复运行不会重复写:
3
- // 已经有、内容一样的跳过;已经有、内容不一样的不覆盖(可能在 Kioku 里改过),要覆盖得明说。
4
- // 本地的文件不删、不改
5
-
6
- import { whoami } from './api.mjs'
7
- import { loadConfig } from './config.mjs'
8
- import { fetchFailure, isRedirect, KiokuFailure, redirectError } from './http.mjs'
9
- import { platformNames, PLATFORMS } from './platforms.mjs'
10
- import { sourceNames, SOURCES, UNSUPPORTED_SOURCES } from './sources.mjs'
11
- import { plain, shownUrl } from './text.mjs'
12
- import { UsageError } from './usage.mjs'
13
-
14
- export const IMPORT_USAGE = `用法:kioku import --from <来源> [--path <目录>] [--platform <平台>] [--dry-run] [--yes] [--overwrite]
15
-
16
- 把平台自带的本地长期记忆迁进 Kioku:先列出每条会放到哪个坐标,确认之后才写。
17
-
18
- --from <来源> ${sourceNames()}
19
- --path <目录> 不用默认的位置时指明(Claude Code 是 projects 目录或某个项目的 memory 目录)
20
- --platform <平台> 用 kioku setup 给这个平台配好的地址与访问密钥(codex、pi、hermes、openclaw、dsh);不写时读环境变量
21
- --dry-run 只列出计划,不写
22
- --yes 不问,直接写(不在终端里运行时要带上)
23
- --overwrite Kioku 里同一个坐标已经有、内容不一样的也覆盖(默认跳过)
24
-
25
- 本地的文件不删、不改。重复运行不会重复写:已经迁过、内容没变的会跳过。
26
- 疑似明文凭据的不写,列出是哪个文件的哪一行:先把值存成凭据,或者从文件里去掉再迁。
27
- 地址与访问密钥读 KIOKU_SERVER_URL 与 KIOKU_API_KEY(Claude Code 的会话里已经配好),或者用 --platform 指明。
28
- 记忆迁进这个访问密钥所属的应用。
29
- 指令文件(AGENTS.md、CLAUDE.md)不是记忆,不迁。
30
- `
31
-
32
- const TIMEOUT = 15_000
33
-
34
- export function parseImportArgs(argv) {
35
- const options = {
36
- from: undefined,
37
- path: undefined,
38
- platform: undefined,
39
- dryRun: false,
40
- yes: false,
41
- overwrite: false,
42
- }
43
- for (let i = 0; i < argv.length; i++) {
44
- const arg = argv[i]
45
- if (arg === '--dry-run') options.dryRun = true
46
- else if (arg === '--yes') options.yes = true
47
- else if (arg === '--overwrite') options.overwrite = true
48
- else if (arg === '--from' || arg === '--path' || arg === '--platform') {
49
- const value = argv[++i]
50
- if (!value) throw new UsageError(`${arg} 后面要写值`)
51
- options[arg.slice(2)] = value
52
- } else throw new UsageError(`不认识的参数 ${arg}`)
53
- }
54
- if (!options.from) throw new UsageError('要写来源:--from <来源>')
55
- if (Object.hasOwn(UNSUPPORTED_SOURCES, options.from)) {
56
- throw new KiokuFailure(UNSUPPORTED_SOURCES[options.from])
57
- }
58
- if (!Object.hasOwn(SOURCES, options.from)) {
59
- throw new UsageError(`不认识的来源 ${options.from},可以用的:${sourceNames()}`)
60
- }
61
- if (options.platform !== undefined && !PLATFORMS[options.platform]?.readConfig) {
62
- throw new UsageError(
63
- `--platform 只收用 kioku setup 写下配置的平台,可以用的:${platformNames()}`,
64
- )
65
- }
66
- return options
67
- }
68
-
69
- async function request({ url, key }, method, path, body) {
70
- let res
71
- let data
72
- try {
73
- res = await fetch(`${url}${path}`, {
74
- method,
75
- headers: {
76
- authorization: `Bearer ${key}`,
77
- ...(body ? { 'content-type': 'application/json' } : {}),
78
- },
79
- ...(body ? { body: JSON.stringify(body) } : {}),
80
- // 不跟着跳转走:访问密钥只发给配置的地址
81
- redirect: 'manual',
82
- signal: AbortSignal.timeout(TIMEOUT),
83
- })
84
- data = await res.json().catch(() => null)
85
- } catch (err) {
86
- throw new KiokuFailure(fetchFailure(err, TIMEOUT))
87
- }
88
- if (isRedirect(res.status)) {
89
- throw new KiokuFailure(redirectError(res.status, res.headers.get('location'), url))
90
- }
91
- return { status: res.status, data }
92
- }
93
-
94
- // 服务端的错误文字压成一行;万一带着访问密钥也盖掉
95
- function serverText(data, status, key) {
96
- const text = typeof data?.error === 'string' ? data.error.split(key).join('***') : ''
97
- return plain(text) || `HTTP ${status}`
98
- }
99
-
100
- // 和 Kioku 里现有的比:new 没有,same 有且正文一样,differs 有但不一样(含读不到正文的机密)
101
- async function compare(config, item) {
102
- const { status, data } = await request(
103
- config,
104
- 'GET',
105
- `/v1/memories?uri=${encodeURIComponent(item.uri)}`,
106
- )
107
- if (status === 404) return { ...item, state: 'new' }
108
- if (status !== 200)
109
- return { ...item, state: 'failed', reason: serverText(data, status, config.key) }
110
- const same = typeof data?.content === 'string' && data.content.trim() === item.content
111
- return { ...item, state: same ? 'same' : 'differs', version: data?.version, id: data?.id }
112
- }
113
-
114
- // 写一条:新建,或者覆盖已有的。返回 { ok } 或 { ok: false, reason, plaintext }
115
- async function write(config, item) {
116
- const fields = {
117
- uri: item.uri,
118
- title: item.title,
119
- content: item.content,
120
- ...(item.disclosure ? { disclosure: item.disclosure } : {}),
121
- }
122
- const { status, data } =
123
- item.state === 'differs'
124
- ? await request(config, 'PATCH', '/v1/memories', {
125
- ...fields,
126
- ...(Number.isInteger(item.version) ? { expectedVersion: item.version } : {}),
127
- ...(item.id ? { expectedId: item.id } : {}),
128
- })
129
- : await request(config, 'POST', '/v1/memories', fields)
130
- if (status === 200 || status === 201) return { ok: true }
131
- const plaintext = Array.isArray(data?.plaintext) ? data.plaintext : null
132
- return { ok: false, reason: serverText(data, status, config.key), plaintext }
133
- }
134
-
135
- const KINDS = { new: '新建', same: '已有,内容一样', differs: '已有,内容不一样' }
136
-
137
- // 问一句是或否;只认 y 开头的回答
138
- export async function confirm(question, { stdin, out }) {
139
- out.write(question)
140
- for await (const chunk of stdin) {
141
- return /^\s*y/i.test(chunk.toString('utf8'))
142
- }
143
- return false
144
- }
145
-
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
- }
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]
181
- const who = await whoami(config)
182
- out.write(
183
- `Kioku:${shownUrl(config.url)},应用 ${plain(who.app.name)}(${plain(who.app.slug)})\n`,
184
- )
185
-
186
- const { root, found, entries } = await source.read({ env, path, app: who.app.slug })
187
- if (!found)
188
- throw new KiokuFailure(`没有找到${source.name}:${plain(root)} 不是目录,用 --path 指明位置`)
189
- out.write(`来源:${source.name}(${plain(root)})\n`)
190
- if (!entries.length) {
191
- out.write('没有可以迁的记忆\n')
192
- return { compared: [], skipped: [], todo: [], empty: true }
193
- }
194
-
195
- // 两条落到同一个坐标的(名字规整之后撞了)只留第一条
196
- const seen = new Set()
197
- const usable = []
198
- const skipped = []
199
- for (const item of entries) {
200
- if (item.skipped) skipped.push(item)
201
- else if (seen.has(item.uri))
202
- skipped.push({ ...item, skipped: `和前面的一条落到同一个坐标 ${item.uri}` })
203
- else {
204
- seen.add(item.uri)
205
- usable.push(item)
206
- }
207
- }
208
- // 一条一个请求:有界并发,几百条也不至于等太久
209
- const compared = await mapLimit(usable, COMPARE_CONCURRENCY, (item) => compare(config, item))
210
-
211
- out.write('\n')
212
- for (const item of compared) {
213
- const kind = item.state === 'failed' ? `读取失败(${item.reason})` : KINDS[item.state]
214
- out.write(`${kind} ${item.uri}\n ${plain(item.title)}\n ← ${plain(item.source)}\n`)
215
- }
216
- for (const item of skipped) out.write(`不迁 ${plain(item.source)}\n ${item.skipped}\n`)
217
-
218
- const count = (state) => compared.filter((item) => item.state === state).length
219
- const todo = compared.filter(
220
- (item) => item.state === 'new' || (item.state === 'differs' && overwrite),
221
- )
222
- out.write(
223
- `\n新建 ${count('new')} 条,已有且一样 ${count('same')} 条,已有但不一样 ${count('differs')} 条` +
224
- `(${overwrite ? '覆盖' : '跳过,要覆盖加 --overwrite'}),不迁 ${skipped.length} 条\n`,
225
- )
226
- return { compared, skipped, todo, empty: false }
227
- }
228
-
229
- // 按计划写入,返回退出码:有没写成的、读取失败的为 1
230
- export async function writeImport(config, { compared, todo }, { out }) {
231
- let written = 0
232
- const failed = []
233
- // 连不上、超时这类不是某一条的问题:停下来,把已经写了多少、还剩多少说清楚,不让它跳出整个命令
234
- let stopped = null
235
- for (const [index, item] of todo.entries()) {
236
- let result
237
- try {
238
- result = await write(config, item)
239
- } catch (err) {
240
- if (!(err instanceof KiokuFailure)) throw err
241
- stopped = { reason: err.message, left: todo.length - index }
242
- break
243
- }
244
- if (result.ok) written++
245
- else failed.push({ item, ...result })
246
- }
247
- out.write(`\n写入 ${written} 条\n`)
248
- for (const { item, reason, plaintext } of failed) {
249
- out.write(`没有写入 ${item.uri}\n ← ${plain(item.source)}\n ${reason}\n`)
250
- // 只说第几行、哪一类,不带值;行号按正文算(文件头之后)
251
- for (const spot of plaintext ?? []) {
252
- out.write(` 正文第 ${Number(spot.line) || '?'} 行:${plain(spot.kind)}\n`)
253
- }
254
- }
255
- if (failed.some((entry) => entry.plaintext)) {
256
- out.write('疑似明文凭据的没有写:把值存成凭据、正文里写占位符,或者从文件里去掉,再运行一次\n')
257
- }
258
- if (stopped) {
259
- out.write(
260
- `${stopped.reason}:还有 ${stopped.left} 条没有写,重新运行会接着写(已经写进去的会跳过)\n`,
261
- )
262
- }
263
- out.write('本地的文件没有动。\n')
264
- return stopped || failed.length || compared.some((item) => item.state === 'failed') ? 1 : 0
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
- }