@kioku-memory/cli 0.2.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/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/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
package/lib/install.mjs CHANGED
@@ -2,6 +2,7 @@
2
2
  // 没给的平台跳过并列出来。插件不替用户装,最后列出要运行的命令
3
3
 
4
4
  import { whoami } from './api.mjs'
5
+ import { conflictToolsText, formatConflicts, removeConflicts, scanConflicts } from './conflicts.mjs'
5
6
  import { configure, pluginSteps, resultsText } from './connect.mjs'
6
7
  import { failureText, keyFormatError, KiokuFailure } from './http.mjs'
7
8
  import { confirm } from './import.mjs'
@@ -29,6 +30,7 @@ ${Object.keys(PLATFORMS)
29
30
  --server-url <地址> Kioku 的服务地址(也可以用 KIOKU_SERVER_URL)
30
31
  -y, --yes 不问,直接写(在终端里运行时默认先列计划再确认)
31
32
  --dry-run 只列计划,不写
33
+ --remove-conflicts 接入前先卸载各平台上已有的冲突记忆工具(Lore 及常见记忆 MCP)
32
34
 
33
35
  各平台照 kioku setup 写下地址与访问密钥、停用自带的长期记忆。
34
36
  Claude Code 的访问密钥在它的 /plugin 里填:这里只核对访问密钥、停用自动记忆。
@@ -36,12 +38,19 @@ Claude Code 的访问密钥在它的 /plugin 里填:这里只核对访问密
36
38
  `
37
39
 
38
40
  export function parseInstallArgs(argv) {
39
- const options = { platforms: [], serverUrl: undefined, yes: false, dryRun: false }
41
+ const options = {
42
+ platforms: [],
43
+ serverUrl: undefined,
44
+ yes: false,
45
+ dryRun: false,
46
+ removeConflicts: false,
47
+ }
40
48
  let given = false
41
49
  for (let i = 0; i < argv.length; i++) {
42
50
  const arg = argv[i]
43
51
  if (arg === '-y' || arg === '--yes') options.yes = true
44
52
  else if (arg === '--dry-run') options.dryRun = true
53
+ else if (arg === '--remove-conflicts') options.removeConflicts = true
45
54
  else if (arg === '--server-url' || arg === '--platforms') {
46
55
  const value = argv[++i]
47
56
  if (!value) throw new UsageError(`${arg} 后面要写值`)
@@ -81,7 +90,7 @@ async function installClaudeCode(url, key, { env, out, cwd }) {
81
90
  if (who.app.runtimeFamily !== PLATFORMS['claude-code'].runtimeFamily) {
82
91
  out.write('! 这个应用的运行时不是 claudecode:在管理界面为 Claude Code 另建一个应用\n')
83
92
  }
84
- const code = await setup(['claude-code'], { env, out, cwd, login: null })
93
+ const code = await setup(['claude-code'], { env, out, cwd, login: null, skipConflicts: true })
85
94
  if (code !== 0) throw new KiokuFailure('停用自动记忆没有成功')
86
95
  out.write('地址与访问密钥要在 Claude Code 的 /plugin 里填(启用插件时会问)\n')
87
96
  }
@@ -93,14 +102,36 @@ export async function install(
93
102
  const options = parseInstallArgs(argv)
94
103
  const url = resolveServerUrl(options, env, null)
95
104
  const plan = installPlan(options.platforms, env)
105
+ const todo = plan.filter((item) => item.key)
106
+ const conflictsByPlatform = new Map()
107
+ for (const { id } of todo) {
108
+ const found = await scanConflicts(id, { env, cwd })
109
+ conflictsByPlatform.set(id, {
110
+ removable: found.filter((c) => c.removable),
111
+ warnings: found.filter((c) => !c.removable),
112
+ })
113
+ }
114
+ const canPromptRemove = !options.yes && stdin.isTTY
115
+ const willRemove = options.removeConflicts || canPromptRemove
116
+
96
117
  out.write(`Kioku:${shownUrl(url)}\n`)
97
118
  for (const item of plan) {
98
119
  const name = PLATFORMS[item.id].name
99
120
  if (item.skip) out.write(` 跳过 ${name}(${item.skip})\n`)
100
121
  else if (item.id === 'claude-code') out.write(` 核对 ${name}:核对访问密钥,停用自动记忆\n`)
101
122
  else out.write(` 接入 ${name}:写下地址与访问密钥,停用自带的长期记忆\n`)
123
+ const entry = conflictsByPlatform.get(item.id)
124
+ if (entry?.removable.length) {
125
+ const action = willRemove
126
+ ? '先卸载再接入'
127
+ : `需先清理:运行 kioku clean ${item.id} 或加 --remove-conflicts`
128
+ out.write(` 冲突 ${name}:发现 ${conflictToolsText(entry.removable)}(${action})\n`)
129
+ out.write(`${formatConflicts(entry.removable, PLATFORMS).join('\n')}\n`)
130
+ }
131
+ for (const w of entry?.warnings ?? []) {
132
+ out.write(` 提示 ${name}:${w.toolName} ${w.summary}\n`)
133
+ }
102
134
  }
103
- const todo = plan.filter((item) => item.key)
104
135
  if (options.dryRun) {
105
136
  out.write('没有写入(--dry-run)\n')
106
137
  return 0
@@ -109,11 +140,17 @@ export async function install(
109
140
  out.write('没有要接入的平台:按上面的变量名给出访问密钥\n')
110
141
  return 1
111
142
  }
112
- if (!options.yes && stdin.isTTY) {
113
- if (!(await confirm(`接入这 ${todo.length} 个平台?[y/N] `, { stdin, out }))) {
143
+ let removeApproved = options.removeConflicts
144
+ if (canPromptRemove) {
145
+ const hasConflicts = todo.some(({ id }) => conflictsByPlatform.get(id)?.removable.length)
146
+ const prompt = hasConflicts
147
+ ? `先卸载发现的冲突并接入这 ${todo.length} 个平台?[y/N] `
148
+ : `接入这 ${todo.length} 个平台?[y/N] `
149
+ if (!(await confirm(prompt, { stdin, out }))) {
114
150
  out.write('没有写入\n')
115
151
  return 0
116
152
  }
153
+ if (hasConflicts) removeApproved = true
117
154
  }
118
155
 
119
156
  const results = plan
@@ -121,6 +158,19 @@ export async function install(
121
158
  .map((item) => ({ ...item, status: 'skipped', reason: item.skip }))
122
159
  for (const { id, key } of todo) {
123
160
  out.write(`\n${PLATFORMS[id].name}\n`)
161
+ const entry = conflictsByPlatform.get(id)
162
+ if (entry?.removable.length) {
163
+ if (!removeApproved) {
164
+ const reason = `存在冲突(${conflictToolsText(entry.removable)}):运行 kioku clean ${id},或加 --remove-conflicts`
165
+ results.push({ id, status: 'failed', reason })
166
+ continue
167
+ }
168
+ const cleanResults = await removeConflicts(entry.removable, { env, cwd, out })
169
+ if (cleanResults.some((r) => !r.ok)) {
170
+ results.push({ id, status: 'failed', reason: '清理冲突没有全部成功' })
171
+ continue
172
+ }
173
+ }
124
174
  try {
125
175
  if (id === 'claude-code') {
126
176
  await installClaudeCode(url, key, { env, out, cwd })
package/lib/kioku.mjs CHANGED
@@ -7,6 +7,7 @@ import { spawn } from 'node:child_process'
7
7
  import { constants } from 'node:os'
8
8
  import { isatty } from 'node:tty'
9
9
 
10
+ import { clean, CLEAN_USAGE } from './clean.mjs'
10
11
  import { killTree, launch } from './command.mjs'
11
12
  import { loadConfig } from './config.mjs'
12
13
  import { IMPORT_USAGE, importMemories } from './import.mjs'
@@ -385,6 +386,7 @@ const OVERVIEW = `用法:kioku <子命令> [参数…]
385
386
  setup 停用平台自带的长期记忆,由 Kioku 接管
386
387
  install 几个平台一起接入,访问密钥从环境变量读(给脚本用)
387
388
  doctor 检查地址、访问密钥与平台的配置
389
+ clean 检测并卸载冲突的记忆工具(Lore 及常见记忆 MCP)
388
390
  import 把平台自带的本地长期记忆迁进 Kioku
389
391
 
390
392
  在终端里不带参数运行 kioku 是交互式的向导:看各平台接到哪一步,按缺的一步步接上。
@@ -442,6 +444,7 @@ export async function main(
442
444
  if (sub === 'setup') return guarded('setup', SETUP_USAGE, setup, rest)
443
445
  if (sub === 'install') return guarded('install', INSTALL_USAGE, install, rest)
444
446
  if (sub === 'doctor') return guarded('doctor', DOCTOR_USAGE, doctor, rest)
447
+ if (sub === 'clean') return guarded('clean', CLEAN_USAGE, clean, rest)
445
448
  if (sub === 'import') return guarded('import', IMPORT_USAGE, importMemories, rest)
446
449
  process.stderr.write(sub === undefined ? OVERVIEW : `kioku:不认识的子命令 ${sub}\n\n${OVERVIEW}`)
447
450
  return 2
package/lib/lifecycle.mjs CHANGED
@@ -84,11 +84,21 @@ export function projectOfAsync(cwd) {
84
84
  // 服务端要注入的上下文文本;没有时为 undefined。只取文本,输出里的其他字段一律不用:
85
85
  // 记忆服务能决定注入什么内容,但不能挡住用户的输入或改变会话
86
86
  export function contextOf(hostOutput) {
87
- if (hostOutput?.mode === 'stdout_json')
88
- return hostOutput.value?.hookSpecificOutput?.additionalContext
87
+ if (hostOutput?.mode === 'stdout_json') {
88
+ return (
89
+ hostOutput.value?.hookSpecificOutput?.additionalContext ??
90
+ hostOutput.value?.injectSteps?.[0]?.systemMessage?.systemMessage
91
+ )
92
+ }
89
93
  if (hostOutput?.mode === 'stdout_text') return hostOutput.value
90
94
  // 没有专门输出格式的运行时:服务端直接给文本
91
- if (hostOutput?.mode === 'return_value') return hostOutput.value?.context
95
+ if (hostOutput?.mode === 'return_value') {
96
+ return (
97
+ hostOutput.value?.systemContext ??
98
+ hostOutput.value?.promptContext ??
99
+ hostOutput.value?.context
100
+ )
101
+ }
92
102
  return undefined
93
103
  }
94
104
 
package/lib/login.mjs CHANGED
@@ -6,6 +6,7 @@
6
6
  import { spawn } from 'node:child_process'
7
7
  import { hostname } from 'node:os'
8
8
 
9
+ import { ensureNoConflicts } from './conflicts.mjs'
9
10
  import { configure, orphanHint } from './connect.mjs'
10
11
  import { fetchFailure, isRedirect, KiokuFailure, redirectError } from './http.mjs'
11
12
  import { platformNames, PLATFORMS } from './platforms.mjs'
@@ -13,7 +14,7 @@ import { resolveServerUrl } from './target.mjs'
13
14
  import { plain } from './text.mjs'
14
15
  import { UsageError } from './usage.mjs'
15
16
 
16
- export const LOGIN_USAGE = `用法:kioku login <平台> [--server-url <地址>] [--no-browser]
17
+ export const LOGIN_USAGE = `用法:kioku login <平台> [--server-url <地址>] [--no-browser] [--remove-conflicts]
17
18
 
18
19
  用浏览器授权给这个平台签发一个访问密钥并配好,不用手动复制:终端显示一个确认码,
19
20
  在 Kioku 管理界面的确认页输入它,选好空间与权限后确认。
@@ -21,6 +22,7 @@ export const LOGIN_USAGE = `用法:kioku login <平台> [--server-url <地址>
21
22
  <平台> ${platformNames()}(Claude Code 的访问密钥在它的 /plugin 里填,不走这里)
22
23
  --server-url <地址> Kioku 的服务地址,例如 https://kioku.example.com(也可以用 KIOKU_SERVER_URL;配过的沿用上次的)
23
24
  --no-browser 不自动打开浏览器,只显示地址
25
+ --remove-conflicts 先卸载平台上已有的冲突记忆工具(Lore 及常见记忆 MCP)再继续
24
26
 
25
27
  只在自己刚运行了这条命令时确认:确认之后,这台机器会拿到一个能按所选权限读写记忆的访问密钥。
26
28
  `
@@ -291,11 +293,12 @@ export async function deviceLoginMany(
291
293
  }
292
294
 
293
295
  export function parseLoginArgs(argv) {
294
- const options = { serverUrl: undefined, browser: true }
296
+ const options = { serverUrl: undefined, browser: true, removeConflicts: false }
295
297
  const names = []
296
298
  for (let i = 0; i < argv.length; i++) {
297
299
  const arg = argv[i]
298
300
  if (arg === '--no-browser') options.browser = false
301
+ else if (arg === '--remove-conflicts') options.removeConflicts = true
299
302
  else if (arg === '--server-url') {
300
303
  options.serverUrl = argv[++i]
301
304
  if (!options.serverUrl) throw new UsageError('--server-url 后面要写地址')
@@ -320,6 +323,7 @@ export async function login(
320
323
  env = process.env,
321
324
  out = process.stdout,
322
325
  cwd = process.cwd(),
326
+ stdin = process.stdin,
323
327
  open,
324
328
  sleep,
325
329
  now,
@@ -330,8 +334,16 @@ export async function login(
330
334
  const platform = PLATFORMS[options.platform]
331
335
  const saved = await Promise.resolve(platform.readConfig?.(env)).catch(() => null)
332
336
  const url = resolveServerUrl(options, env, saved)
333
- // 申请之前先看这个平台的配置写不写得进去:访问密钥只在签发时给一次
337
+ // 申请之前先看这个平台的配置写不写得进去、有没有冲突:访问密钥只在签发时给一次
334
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
335
347
  const key = await deviceLogin(
336
348
  { url, runtimeFamily: platform.runtimeFamily },
337
349
  { out, open, browser: options.browser, sleep, now, ...(clientName ? { clientName } : {}) },
@@ -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
+ }