@kioku-memory/cli 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.
package/lib/login.mjs CHANGED
@@ -6,13 +6,15 @@
6
6
  import { spawn } from 'node:child_process'
7
7
  import { hostname } from 'node:os'
8
8
 
9
+ import { ensureNoConflicts } from './conflicts.mjs'
10
+ import { configure, orphanHint } from './connect.mjs'
9
11
  import { fetchFailure, isRedirect, KiokuFailure, redirectError } from './http.mjs'
10
12
  import { platformNames, PLATFORMS } from './platforms.mjs'
11
13
  import { resolveServerUrl } from './target.mjs'
12
14
  import { plain } from './text.mjs'
13
15
  import { UsageError } from './usage.mjs'
14
16
 
15
- export const LOGIN_USAGE = `用法:kioku login <平台> [--server-url <地址>] [--no-browser]
17
+ export const LOGIN_USAGE = `用法:kioku login <平台> [--server-url <地址>] [--no-browser] [--remove-conflicts]
16
18
 
17
19
  用浏览器授权给这个平台签发一个访问密钥并配好,不用手动复制:终端显示一个确认码,
18
20
  在 Kioku 管理界面的确认页输入它,选好空间与权限后确认。
@@ -20,6 +22,7 @@ export const LOGIN_USAGE = `用法:kioku login <平台> [--server-url <地址>
20
22
  <平台> ${platformNames()}(Claude Code 的访问密钥在它的 /plugin 里填,不走这里)
21
23
  --server-url <地址> Kioku 的服务地址,例如 https://kioku.example.com(也可以用 KIOKU_SERVER_URL;配过的沿用上次的)
22
24
  --no-browser 不自动打开浏览器,只显示地址
25
+ --remove-conflicts 先卸载平台上已有的冲突记忆工具(Lore 及常见记忆 MCP)再继续
23
26
 
24
27
  只在自己刚运行了这条命令时确认:确认之后,这台机器会拿到一个能按所选权限读写记忆的访问密钥。
25
28
  `
@@ -69,12 +72,33 @@ function seconds(value, fallback, min, max) {
69
72
  return Math.min(max, Math.max(min, number))
70
73
  }
71
74
 
72
- // 申请:返回设备码、确认码、确认页的地址与时限
73
- export async function requestGrant(url, { runtimeFamily, clientName }) {
75
+ // 服务端不认一次申请几个平台的写法:退回逐个平台申请
76
+ export class LegacyServer extends KiokuFailure {}
77
+
78
+ // 旧的服务端只认单个平台的写法,收到 platforms 时按校验失败回 400,第一条问题是缺 runtimeFamily
79
+ // (「runtimeFamily:…」)。别的 400 是申请本身有问题,照原样报
80
+ function legacyRejection(data) {
81
+ return typeof data?.error === 'string' && /^runtimeFamily[::]/.test(data.error)
82
+ }
83
+
84
+ // 一次申请最多几个平台,与服务端的上限一致
85
+ export const MAX_PLATFORMS = 8
86
+
87
+ // 申请:返回设备码、确认码、确认页的地址与时限。body 是单平台的 { runtimeFamily, clientName },
88
+ // 或几个平台的 { platforms: [{ runtimeFamily }], clientName }
89
+ export async function requestGrant(url, body) {
90
+ const { clientName, ...rest } = body
74
91
  const { status, data } = await post(url, '/v1/device/authorize', {
75
- runtimeFamily,
92
+ ...rest,
76
93
  ...(clientName ? { clientName } : {}),
77
94
  })
95
+ if (status === 400 && Array.isArray(body.platforms) && legacyRejection(data)) {
96
+ throw new LegacyServer('服务端版本较旧,需要逐个确认')
97
+ }
98
+ if (status === 400) {
99
+ const reason = typeof data?.error === 'string' ? plain(data.error) : ''
100
+ throw new KiokuFailure(`Kioku 拒绝了这次申请${reason ? `:${reason}` : ''}`)
101
+ }
78
102
  if (status === 404) {
79
103
  throw new KiokuFailure(
80
104
  '这个 Kioku 还不支持浏览器授权:升级服务端,或者用 kioku setup 手动填访问密钥',
@@ -100,9 +124,9 @@ export async function requestGrant(url, { runtimeFamily, clientName }) {
100
124
  }
101
125
  }
102
126
 
103
- // 等确认:按服务端给的间隔轮询,返回访问密钥与应用;被拒绝、过期时抛 KiokuFailure。
127
+ // 等确认:按服务端给的间隔轮询,确认了返回服务端的整个回答;被拒绝、过期时抛 KiokuFailure。
104
128
  // sleep 与 now 可以换掉,给用例用;now 要是只往前走的钟,系统时间被改不影响什么时候停
105
- export async function waitForKey(
129
+ async function waitForApproval(
106
130
  url,
107
131
  grant,
108
132
  {
@@ -146,9 +170,7 @@ export async function waitForKey(
146
170
  if (data?.status === 'denied') {
147
171
  throw new KiokuFailure('申请被拒绝了,或者确认之后确认人的权限变了:没有签发访问密钥')
148
172
  }
149
- if (data?.status === 'approved' && typeof data.key === 'string' && data.key) {
150
- return { key: data.key, app: data.app ?? {} }
151
- }
173
+ if (data?.status === 'approved') return data
152
174
  if (data?.status === 'expired') break
153
175
  throw new KiokuFailure('Kioku 的响应格式不对')
154
176
  }
@@ -159,9 +181,46 @@ export async function waitForKey(
159
181
  )
160
182
  }
161
183
 
184
+ // 等一个平台的申请被确认,返回访问密钥与应用
185
+ export async function waitForKey(url, grant, options) {
186
+ const data = await waitForApproval(url, grant, options)
187
+ if (typeof data.key !== 'string' || !data.key) throw new KiokuFailure('Kioku 的响应格式不对')
188
+ return { key: data.key, app: data.app ?? {} }
189
+ }
190
+
191
+ // 几个平台一起的申请被确认之后,每个平台的结果:按申请的顺序,
192
+ // { runtimeFamily, status: 'issued', key, app } | { runtimeFamily, status: 'skipped' } | { runtimeFamily, status: 'denied', reason }。
193
+ // 服务端没提到的平台算跳过,不认识的平台、重复的项不收;签发了却不像访问密钥的算响应不对
194
+ export async function waitForKeys(url, grant, families, options) {
195
+ const data = await waitForApproval(url, grant, options)
196
+ // 已经确认了:响应读不懂时,服务端可能已经签发了几个没人拿着的访问密钥
197
+ const malformed = () => new KiokuFailure(`Kioku 的响应格式不对。${ORPHAN_HINT}`)
198
+ if (!Array.isArray(data.keys)) throw malformed()
199
+ const byFamily = new Map()
200
+ for (const item of data.keys) {
201
+ const family = item?.runtimeFamily
202
+ if (!families.includes(family) || byFamily.has(family)) continue
203
+ if (item.status === 'issued') {
204
+ if (typeof item.key !== 'string' || !item.key) throw malformed()
205
+ byFamily.set(family, {
206
+ runtimeFamily: family,
207
+ status: 'issued',
208
+ key: item.key,
209
+ app: item.app ?? {},
210
+ })
211
+ } else if (item.status === 'denied') {
212
+ const reason = typeof item.reason === 'string' ? plain(item.reason) : ''
213
+ byFamily.set(family, { runtimeFamily: family, status: 'denied', reason })
214
+ } else byFamily.set(family, { runtimeFamily: family, status: 'skipped' })
215
+ }
216
+ return families.map(
217
+ (family) => byFamily.get(family) ?? { runtimeFamily: family, status: 'skipped' },
218
+ )
219
+ }
220
+
162
221
  // 用系统默认的浏览器打开地址;打不开就算了,地址已经显示在终端里。都不经过 shell:
163
222
  // Windows 上用 rundll32,不用 cmd 的 start(它会把地址里的 & 这类符号当成命令)
164
- function openBrowser(address) {
223
+ export function openBrowser(address) {
165
224
  const [command, args] =
166
225
  process.platform === 'darwin'
167
226
  ? ['open', [address]]
@@ -177,30 +236,69 @@ function openBrowser(address) {
177
236
  }
178
237
  }
179
238
 
180
- // 走一遍浏览器授权,返回访问密钥。提示写到 out,访问密钥不写
181
- export async function deviceLogin(
182
- { url, runtimeFamily },
183
- { out, open = openBrowser, browser = true, clientName = hostname(), sleep, now } = {},
184
- ) {
185
- // 机器名是自报的:去掉控制字符,太长就截断,服务端只把它显示在确认页上
186
- const name = Array.from(plain(clientName)).slice(0, 64).join('')
187
- const grant = await requestGrant(url, { runtimeFamily, clientName: name })
239
+ // 本地网络给主机名加的后缀,不算机器的名字
240
+ const HOST_SUFFIX = /\.(?:local|localdomain|lan|home|internal)$/i
241
+
242
+ // 机器名是自报的:去掉控制字符与 .local 这类后缀,太长就截断;什么都不剩时用 kioku-cli。
243
+ // 服务端把它显示在确认页上,新建的应用默认叫「平台名 · 机器名」
244
+ export function machineName(clientName) {
245
+ const name = Array.from(plain(clientName).replace(HOST_SUFFIX, '').trim())
246
+ .slice(0, 64)
247
+ .join('')
248
+ .trim()
249
+ return name || 'kioku-cli'
250
+ }
251
+
252
+ // 显示确认码与确认页,打开浏览器
253
+ function showGrant(grant, { out, open, browser }) {
188
254
  out.write(`确认码:${plain(grant.userCode)}\n`)
189
255
  // 显示的和打开的是同一个地址
190
256
  out.write(`在浏览器里打开 ${plain(grant.verificationUrl)},登录后输入这个确认码\n`)
191
257
  out.write(`等待确认(${Math.ceil(grant.expiresIn / 60)} 分钟内有效)…\n`)
192
258
  if (browser) open(grant.verificationUrl)
259
+ }
260
+
261
+ // 走一遍浏览器授权,返回访问密钥。提示写到 out,访问密钥不写
262
+ export async function deviceLogin(
263
+ { url, runtimeFamily },
264
+ { out, open = openBrowser, browser = true, clientName = hostname(), sleep, now } = {},
265
+ ) {
266
+ const grant = await requestGrant(url, { runtimeFamily, clientName: machineName(clientName) })
267
+ showGrant(grant, { out, open, browser })
193
268
  const { key, app } = await waitForKey(url, grant, { sleep, now })
194
269
  out.write(`✓ 已确认:应用 ${plain(app.name ?? '')}(${plain(app.slug ?? '')})\n`)
195
270
  return key
196
271
  }
197
272
 
273
+ // 几个平台一起申请,只确认一次。返回 waitForKeys 的结果(按去重后的顺序);服务端不认这种写法时抛 LegacyServer。
274
+ // 一次最多 MAX_PLATFORMS 个,多了由调用方分批(connect.mjs),这里不发超出上限的申请
275
+ export async function deviceLoginMany(
276
+ { url, runtimeFamilies },
277
+ { out, open = openBrowser, browser = true, clientName = hostname(), sleep, now } = {},
278
+ ) {
279
+ const families = [...new Set(runtimeFamilies)]
280
+ if (!families.length || families.length > MAX_PLATFORMS) {
281
+ throw new KiokuFailure(`一次申请 1 到 ${MAX_PLATFORMS} 个平台`)
282
+ }
283
+ const grant = await requestGrant(url, {
284
+ platforms: families.map((runtimeFamily) => ({ runtimeFamily })),
285
+ clientName: machineName(clientName),
286
+ })
287
+ showGrant(grant, { out, open, browser })
288
+ const results = await waitForKeys(url, grant, families, { sleep, now })
289
+ // 确认了也可能一个都没签发:取走时照签发规则再核对,全都没过(例如确认人已停用)
290
+ const issued = results.filter((item) => item.status === 'issued').length
291
+ out.write(issued ? `✓ 已确认,签发了 ${issued} 个访问密钥\n` : '✗ 已确认,但没有签发访问密钥\n')
292
+ return results
293
+ }
294
+
198
295
  export function parseLoginArgs(argv) {
199
- const options = { serverUrl: undefined, browser: true }
296
+ const options = { serverUrl: undefined, browser: true, removeConflicts: false }
200
297
  const names = []
201
298
  for (let i = 0; i < argv.length; i++) {
202
299
  const arg = argv[i]
203
300
  if (arg === '--no-browser') options.browser = false
301
+ else if (arg === '--remove-conflicts') options.removeConflicts = true
204
302
  else if (arg === '--server-url') {
205
303
  options.serverUrl = argv[++i]
206
304
  if (!options.serverUrl) throw new UsageError('--server-url 后面要写地址')
@@ -225,6 +323,7 @@ export async function login(
225
323
  env = process.env,
226
324
  out = process.stdout,
227
325
  cwd = process.cwd(),
326
+ stdin = process.stdin,
228
327
  open,
229
328
  sleep,
230
329
  now,
@@ -235,23 +334,26 @@ export async function login(
235
334
  const platform = PLATFORMS[options.platform]
236
335
  const saved = await Promise.resolve(platform.readConfig?.(env)).catch(() => null)
237
336
  const url = resolveServerUrl(options, env, saved)
238
- // 申请之前先看这个平台的配置写不写得进去:访问密钥只在签发时给一次
337
+ // 申请之前先看这个平台的配置写不写得进去、有没有冲突:访问密钥只在签发时给一次
239
338
  await platform.preflight?.({ env, cwd })
339
+ const conflictStatus = await ensureNoConflicts(options.platform, platform.name, {
340
+ env,
341
+ cwd,
342
+ out,
343
+ stdin,
344
+ remove: options.removeConflicts,
345
+ })
346
+ if (conflictStatus === 'cancelled') return 0
240
347
  const key = await deviceLogin(
241
348
  { url, runtimeFamily: platform.runtimeFamily },
242
349
  { out, open, browser: options.browser, sleep, now, ...(clientName ? { clientName } : {}) },
243
350
  )
244
351
  // 拿到的访问密钥交给这个平台的 setup:核对、写文件都照它的规矩
245
352
  try {
246
- return await platform.setup(
247
- { serverUrl: url, dryRun: false, undo: false, check: true },
248
- { env, out, cwd, readKey: async () => key, plain, login: null },
249
- )
353
+ return await configure(options.platform, { url, key }, { env, out, cwd }, { hints: true })
250
354
  } catch (err) {
251
355
  if (!(err instanceof KiokuFailure)) throw err
252
356
  // 访问密钥已经签发、却没有写下来:说清楚,别让它悄悄留着
253
- throw new KiokuFailure(
254
- `${err.message}。访问密钥已经签发、但没有写下:到管理界面的应用页吊销它,解决上面的问题后重新运行`,
255
- )
357
+ throw new KiokuFailure(`${err.message}。${orphanHint()}`)
256
358
  }
257
359
  }
package/lib/openclaw.mjs CHANGED
@@ -201,7 +201,7 @@ export async function setupOpenclaw(options, io) {
201
201
  out.write(
202
202
  '插件装了没有、记忆槽位选的是什么没有查出来(openclaw plugins inspect 失败了):用 kioku doctor openclaw 再看一次\n',
203
203
  )
204
- } else if (!state) {
204
+ } else if (!state && io.hints !== false) {
205
205
  out.write(`接下来装上插件:openclaw plugins install ${SOURCE}\n`)
206
206
  if (todo.length) out.write('装好之后再运行一次 kioku setup openclaw。\n')
207
207
  }
@@ -246,3 +246,11 @@ export async function inspectOpenclaw({ env }, { ok, warn, note }) {
246
246
  '工作区里的 MEMORY.md 有内容时 OpenClaw 仍会放进提示:用 kioku import --from openclaw 迁走后清空它',
247
247
  )
248
248
  }
249
+
250
+ // 给向导的面板:插件装没装、记忆槽位选的是不是 kioku。没有 openclaw 命令、没查出来时为 null
251
+ export async function statusOpenclaw({ env }) {
252
+ const state = await pluginState(env)
253
+ if (state === null || state === undefined) return { plugin: null, memory: null }
254
+ if (!state) return { plugin: false, memory: 'on' }
255
+ return { plugin: state.enabled && state.loaded, memory: state.slot ? 'off' : 'on' }
256
+ }
@@ -0,0 +1,144 @@
1
+ // OpenCode 这个平台的 kioku setup 与 kioku doctor。
2
+ // OpenCode 没有自带的长期记忆要停用,插件会在 config 钩子里按需注册 Kioku 的远程 MCP 服务,
3
+ // 所以 setup 做两件事:把服务地址与访问密钥写进本机的文件(只给本人读写),并在 opencode.json 的 plugin 列表里登记插件
4
+
5
+ import { homedir } from 'node:os'
6
+ import { join } from 'node:path'
7
+
8
+ import { readSettings, writeSettings } from './files.mjs'
9
+ import { KiokuFailure } from './http.mjs'
10
+ import { profileFile, readProfile, removeProfile, writeProfile } from './profile.mjs'
11
+ import { resolveTarget } from './target.mjs'
12
+
13
+ export const OPENCODE_PLUGIN = '@kioku-memory/plugin-opencode'
14
+
15
+ export function opencodeHome(env) {
16
+ if (env.OPENCODE_CONFIG_DIR) return env.OPENCODE_CONFIG_DIR
17
+ return join(env.XDG_CONFIG_HOME || join(env.HOME || homedir(), '.config'), 'opencode')
18
+ }
19
+
20
+ function opencodeConfigFile(env) {
21
+ return join(opencodeHome(env), 'opencode.json')
22
+ }
23
+
24
+ function isKiokuPlugin(entry) {
25
+ if (typeof entry !== 'string') return false
26
+ return entry.includes('plugin-opencode') || entry.includes('kioku-plugins')
27
+ }
28
+
29
+ function pluginInstalled(settings) {
30
+ return Array.isArray(settings?.plugin) && settings.plugin.some(isKiokuPlugin)
31
+ }
32
+
33
+ function checkPluginShape(settings, file) {
34
+ if (settings.plugin !== undefined && !Array.isArray(settings.plugin)) {
35
+ throw new KiokuFailure(`${file} 里的 plugin 不是数组,没有改动它`)
36
+ }
37
+ }
38
+
39
+ function ensurePlugin(settings, add) {
40
+ const list = Array.isArray(settings?.plugin) ? [...settings.plugin] : []
41
+ if (add) {
42
+ if (list.some(isKiokuPlugin)) return settings
43
+ return { ...settings, plugin: [...list, OPENCODE_PLUGIN] }
44
+ }
45
+ if (!list.some(isKiokuPlugin)) return settings
46
+ const filtered = list.filter((entry) => !isKiokuPlugin(entry))
47
+ const next = { ...settings }
48
+ if (filtered.length) next.plugin = filtered
49
+ else delete next.plugin
50
+ return next
51
+ }
52
+
53
+ export async function preflightOpenCode({ env }) {
54
+ const file = opencodeConfigFile(env)
55
+ const { settings } = await readSettings(file)
56
+ checkPluginShape(settings, file)
57
+ }
58
+
59
+ export async function setupOpenCode(options, io) {
60
+ const { env, out } = io
61
+ const profile = profileFile('opencode', env)
62
+ const file = opencodeConfigFile(env)
63
+
64
+ if (options.undo) {
65
+ const { settings, text } = await readSettings(file)
66
+ checkPluginShape(settings, file)
67
+ if (pluginInstalled(settings)) {
68
+ const next = ensurePlugin(settings, false)
69
+ out.write(`${file}:从 plugin 中移除 ${OPENCODE_PLUGIN}\n`)
70
+ if (!options.dryRun) await writeSettings(file, next, text)
71
+ } else if (text !== null) {
72
+ out.write(`${file} 里没有登记 Kioku 插件,不用改\n`)
73
+ }
74
+
75
+ if (options.dryRun) out.write(`${profile}:删掉\n没有写入(--dry-run)\n`)
76
+ else if (await removeProfile('opencode', env)) out.write(`已删掉 ${profile}\n`)
77
+ else out.write(`${profile} 本来就没有\n`)
78
+ return 0
79
+ }
80
+
81
+ await preflightOpenCode({ env })
82
+ const { url, key, saved } = await resolveTarget({ id: 'opencode', name: 'OpenCode' }, options, {
83
+ ...io,
84
+ beforeLogin: () => preflightOpenCode({ env }),
85
+ })
86
+ const sameProfile = Boolean(saved && saved.url === url && saved.key === key)
87
+ if (sameProfile) out.write(`${profile} 不用改\n`)
88
+ else out.write(`${profile}:写入服务地址与访问密钥(只给本人读写)\n`)
89
+
90
+ const { settings, text } = await readSettings(file)
91
+ checkPluginShape(settings, file)
92
+ const needPlugin = !pluginInstalled(settings)
93
+ if (needPlugin) out.write(`${file}:在 plugin 中加入 ${OPENCODE_PLUGIN}\n`)
94
+ else out.write(`${file} 不用改\n`)
95
+
96
+ if (options.dryRun) {
97
+ out.write('没有写入(--dry-run)\n')
98
+ return 0
99
+ }
100
+
101
+ if (!sameProfile) await writeProfile('opencode', { url, key }, env)
102
+ if (needPlugin) {
103
+ const backedUp = await writeSettings(file, ensurePlugin(settings, true), text)
104
+ if (backedUp) out.write(`原配置已备份到 ${file}.kioku-backup\n`)
105
+ }
106
+ out.write('OpenCode 已配好,重启 OpenCode 后生效。\n')
107
+ return 0
108
+ }
109
+
110
+ export async function inspectOpenCode({ env, cwd }, { ok, warn }) {
111
+ const profile = await readProfile('opencode', env).catch(() => null)
112
+ if (!profile) {
113
+ warn('没有 kioku setup opencode 写下的地址与访问密钥,插件不会生效:运行 kioku setup opencode')
114
+ }
115
+
116
+ const user = await readSettings(opencodeConfigFile(env))
117
+ const local = await readSettings(join(cwd, 'opencode.json')).catch(() => ({}))
118
+ if (pluginInstalled(user.settings) || pluginInstalled(local.settings)) {
119
+ ok('OpenCode 里登记了 kioku 插件')
120
+ } else {
121
+ warn(
122
+ `OpenCode 里没有登记 kioku 插件:运行 kioku setup opencode,或在 opencode.json 中加入 ${OPENCODE_PLUGIN}`,
123
+ )
124
+ }
125
+
126
+ for (const [name, cfg] of [
127
+ [opencodeConfigFile(env), user.settings],
128
+ [join(cwd, 'opencode.json'), local.settings],
129
+ ]) {
130
+ if (cfg?.mcp && typeof cfg.mcp === 'object' && Object.hasOwn(cfg.mcp, 'kioku')) {
131
+ warn(`${name} 里自己写了 mcp.kioku,它会覆盖插件注册的地址与访问密钥:建议去掉它`)
132
+ }
133
+ }
134
+ ok('OpenCode 没有自带的长期记忆要停用')
135
+ }
136
+
137
+ export async function statusOpenCode({ env, cwd }) {
138
+ const user = await readSettings(opencodeConfigFile(env)).catch(() => ({}))
139
+ const local = await readSettings(join(cwd, 'opencode.json')).catch(() => ({}))
140
+ return {
141
+ plugin: pluginInstalled(user.settings) || pluginInstalled(local.settings),
142
+ memory: 'none',
143
+ }
144
+ }