@kioku-memory/plugin-opencode 0.1.0 → 0.5.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/conflicts.mjs DELETED
@@ -1,1303 +0,0 @@
1
- // 冲突记忆工具(Lore 与常见记忆 MCP)的只读探测与按平台清理。
2
- // 只解除当前目标平台上的冲突配置或插件挂载,不跨平台改动,不删用户服务端数据目录(如 ~/.lore/docker)。
3
-
4
- import { lstat, rm, unlink } from 'node:fs/promises'
5
- import { homedir } from 'node:os'
6
- import { join } from 'node:path'
7
-
8
- import { agyHome, agyMcpFile } from './agy.mjs'
9
- import { bracketDelta, codexHome, headerOf } from './codex.mjs'
10
- import { capture, hasCommand } from './command.mjs'
11
- import { dshHome } from './dsh.mjs'
12
- import { readSettings, readText, safeWrite, serialize } from './files.mjs'
13
- import { geminiHome, geminiSettingsFile } from './gemini.mjs'
14
- import { hermesHome, withEnv } from './hermes.mjs'
15
- import { KiokuFailure } from './http.mjs'
16
- import { confirm } from './import.mjs'
17
- import { opencodeHome } from './opencode.mjs'
18
- import { piHome } from './pi.mjs'
19
- import { plain } from './text.mjs'
20
-
21
- export const CONFLICT_TOOLS = {
22
- lore: 'Lore',
23
- mem0: 'Mem0',
24
- supermemory: 'Supermemory',
25
- 'mcp-memory': 'MCP Memory',
26
- cipher: 'Cipher',
27
- 'claude-mem': 'Claude-Mem',
28
- 'unknown-memory': '疑似记忆 MCP',
29
- }
30
-
31
- const LORE_ENV_KEYS = [
32
- 'LORE_BASE_URL',
33
- 'LORE_API_TOKEN',
34
- 'LORE_HOME',
35
- 'LORE_CLIENT_TYPE',
36
- 'LORE_SKILLS_ENABLED',
37
- ]
38
- const LORE_GUIDANCE_IMPORT =
39
- /^(@~\/\.claude\/lore-guidance\.md|@import ~\/\.claude\/lore-guidance\.md)$/
40
- const LORE_OPENCODE_MARKER = '@lore-managed-opencode-plugin'
41
- const DSH_BEGIN_MARKER = '# >>> lore (managed) >>>'
42
- const DSH_END_MARKER = '# <<< lore (managed) <<<'
43
-
44
- function homeOf(env) {
45
- return env.HOME || homedir()
46
- }
47
-
48
- function claudeHome(env) {
49
- return env.CLAUDE_CONFIG_DIR || join(homeOf(env), '.claude')
50
- }
51
-
52
- function claudeJsonFile(env) {
53
- return env.CLAUDE_CONFIG_DIR
54
- ? join(env.CLAUDE_CONFIG_DIR, '.claude.json')
55
- : join(homeOf(env), '.claude.json')
56
- }
57
-
58
- function openclawHome(env) {
59
- return join(env.OPENCLAW_HOME || homeOf(env), '.openclaw')
60
- }
61
-
62
- function loreHomeOf(env) {
63
- return env.LORE_HOME?.trim() || join(homeOf(env), '.lore')
64
- }
65
-
66
- // 文本或 JSON 设置里有没有带密钥:有的话修改文件时不留明文备份
67
- function hasJsonSecret(value) {
68
- if (!value || typeof value !== 'object') return false
69
- if (Array.isArray(value)) return value.some(hasJsonSecret)
70
- for (const [k, v] of Object.entries(value)) {
71
- if (typeof v === 'string') {
72
- if (/\bBearer\s+\S+/i.test(v)) return true
73
- if (/(?:authorization|api[_-]?token|api[_-]?key|token|secret)/i.test(k) && v.trim()) {
74
- return true
75
- }
76
- } else if (v && typeof v === 'object' && hasJsonSecret(v)) {
77
- return true
78
- }
79
- }
80
- return false
81
- }
82
-
83
- function backupAllowed(file, hasSecret, noBackupFiles) {
84
- if (hasSecret || noBackupFiles?.has(file)) {
85
- noBackupFiles?.add(file)
86
- return false
87
- }
88
- return true
89
- }
90
-
91
- function hasTextSecret(text) {
92
- return (
93
- /\bBearer\s+\S+/i.test(text) ||
94
- /\b(?:api[_-]?token|api[_-]?key|authorization)\s*[:=]\s*["']?[^"'\s#]+/i.test(text)
95
- )
96
- }
97
-
98
- function serializeSpec(entry) {
99
- if (typeof entry === 'string') return entry.toLowerCase()
100
- try {
101
- return JSON.stringify(entry ?? {}).toLowerCase()
102
- } catch {
103
- return ''
104
- }
105
- }
106
-
107
- // 识别 MCP 条目属于哪款记忆工具;只命中泛用名 memory 但特征不明的仅告警不自动删
108
- export function matchMcpTool(name, entry) {
109
- const key = String(name ?? '')
110
- .trim()
111
- .toLowerCase()
112
- const spec = serializeSpec(entry)
113
-
114
- if (
115
- key === 'lore' ||
116
- key === 'lore-skills' ||
117
- key === 'lore-memory' ||
118
- /lore-mcp|@loremem\/|lore-memory|\/api\/mcp\?client_type=/.test(spec)
119
- ) {
120
- return { tool: 'lore', toolName: CONFLICT_TOOLS.lore, removable: true }
121
- }
122
- if (
123
- key === 'mem0' ||
124
- key === 'mem0-mcp' ||
125
- key === 'openmemory' ||
126
- /mem0-mcp|@mem0\/|openmemory|mem0ai/.test(spec)
127
- ) {
128
- return { tool: 'mem0', toolName: CONFLICT_TOOLS.mem0, removable: true }
129
- }
130
- if (key === 'supermemory' || /supermemory\.ai|@supermemory\//.test(spec)) {
131
- return { tool: 'supermemory', toolName: CONFLICT_TOOLS.supermemory, removable: true }
132
- }
133
- if (
134
- /@byterover\/cipher|byterover-cipher/.test(spec) ||
135
- (key === 'cipher' && /\bcipher\b/.test(spec))
136
- ) {
137
- return { tool: 'cipher', toolName: CONFLICT_TOOLS.cipher, removable: true }
138
- }
139
- if (key === 'claude-mem' || /claude-mem|thedotmack\/claude-mem/.test(spec)) {
140
- return { tool: 'claude-mem', toolName: CONFLICT_TOOLS['claude-mem'], removable: true }
141
- }
142
- if (/@modelcontextprotocol\/server-memory|mcp-server-memory/.test(spec)) {
143
- return { tool: 'mcp-memory', toolName: CONFLICT_TOOLS['mcp-memory'], removable: true }
144
- }
145
- if (key === 'memory' || key === 'memory-mcp' || key === 'long-term-memory') {
146
- return {
147
- tool: 'unknown-memory',
148
- toolName: CONFLICT_TOOLS['unknown-memory'],
149
- removable: false,
150
- hint: '未命中已知记忆服务包名,确认不需要后可手动删除',
151
- }
152
- }
153
- return null
154
- }
155
-
156
- async function readJsonSafe(file) {
157
- try {
158
- return { ok: true, ...(await readSettings(file)) }
159
- } catch (err) {
160
- return { ok: false, error: err instanceof KiokuFailure ? err.message : `无法读取 ${file}` }
161
- }
162
- }
163
-
164
- async function scanJsonMcp(items, { platform, file, containerKey = 'mcpServers', onRemove }) {
165
- const res = await readJsonSafe(file)
166
- if (!res.ok || res.text === null) return
167
- const container = res.settings?.[containerKey]
168
- if (!container || typeof container !== 'object' || Array.isArray(container)) return
169
-
170
- for (const [name, entry] of Object.entries(container)) {
171
- const matched = matchMcpTool(name, entry)
172
- if (!matched) continue
173
- items.push({
174
- id: `${platform}:${matched.tool}:mcp:${file}#${name}`,
175
- platform,
176
- tool: matched.tool,
177
- toolName: matched.toolName,
178
- kind: matched.removable ? 'mcp' : 'warning',
179
- summary: `${containerKey}.${name}(${plain(file)})`,
180
- removable: matched.removable,
181
- ...(matched.hint ? { hint: matched.hint } : {}),
182
- ...(matched.removable
183
- ? {
184
- remove: async ({ noBackupFiles } = {}) => {
185
- if (onRemove) await onRemove(name, matched)
186
- const latest = await readSettings(file)
187
- const current = latest.settings?.[containerKey]
188
- if (
189
- !current ||
190
- typeof current !== 'object' ||
191
- Array.isArray(current) ||
192
- !Object.hasOwn(current, name)
193
- ) {
194
- return { changed: false, message: `${plain(file)} 里的 ${name} 已不在` }
195
- }
196
- const next = { ...latest.settings }
197
- const nextContainer = { ...current }
198
- delete nextContainer[name]
199
- if (Object.keys(nextContainer).length) next[containerKey] = nextContainer
200
- else delete next[containerKey]
201
- await safeWrite(file, serialize(next, latest.text), latest.text, {
202
- backup: backupAllowed(file, hasJsonSecret(latest.settings), noBackupFiles),
203
- })
204
- return { changed: true, message: `已从 ${plain(file)} 移除 ${containerKey}.${name}` }
205
- },
206
- }
207
- : {}),
208
- })
209
- }
210
- }
211
-
212
- async function scanPathRemoval(
213
- items,
214
- { platform, tool, toolName, kind, target, summary, checkDir },
215
- ) {
216
- let st
217
- try {
218
- st = await lstat(target)
219
- } catch {
220
- return
221
- }
222
- if (st.isSymbolicLink()) {
223
- items.push({
224
- id: `${platform}:${tool}:${kind}:${target}`,
225
- platform,
226
- tool,
227
- toolName,
228
- kind,
229
- summary,
230
- removable: true,
231
- remove: async () => {
232
- try {
233
- await unlink(target)
234
- return { changed: true, message: `已移除符号链接 ${plain(target)}` }
235
- } catch (err) {
236
- if (err?.code === 'ENOENT') return { changed: false, message: `${plain(target)} 已不在` }
237
- throw new KiokuFailure(`无法移除 ${plain(target)}`)
238
- }
239
- },
240
- })
241
- return
242
- }
243
- if (st.isDirectory()) {
244
- const owned = checkDir ? await checkDir(target) : true
245
- if (owned) {
246
- items.push({
247
- id: `${platform}:${tool}:${kind}:${target}`,
248
- platform,
249
- tool,
250
- toolName,
251
- kind,
252
- summary,
253
- removable: true,
254
- remove: async () => {
255
- await rm(target, { recursive: true, force: true })
256
- return { changed: true, message: `已移除目录 ${plain(target)}` }
257
- },
258
- })
259
- } else {
260
- items.push({
261
- id: `${platform}:${tool}:warn:${target}`,
262
- platform,
263
- tool,
264
- toolName,
265
- kind: 'warning',
266
- summary: `${summary}(不是符号链接且缺少托管标记,未自动删除)`,
267
- removable: false,
268
- })
269
- }
270
- return
271
- }
272
- items.push({
273
- id: `${platform}:${tool}:warn:${target}`,
274
- platform,
275
- tool,
276
- toolName,
277
- kind: 'warning',
278
- summary: `${summary}(非预期文件类型,未自动删除)`,
279
- removable: false,
280
- })
281
- }
282
-
283
- async function hasJsonName(file, expectedNames) {
284
- const res = await readJsonSafe(file)
285
- if (!res.ok || res.text === null) return false
286
- return expectedNames.includes(String(res.settings?.name ?? '').toLowerCase())
287
- }
288
-
289
- // ── Antigravity (agy) ────────────────────────────────────────────────────────
290
-
291
- async function scanAgyConflicts(items, { env, cwd }) {
292
- const home = agyHome(env)
293
- await scanJsonMcp(items, { platform: 'agy', file: agyMcpFile(env), containerKey: 'mcpServers' })
294
-
295
- for (const [tool, dirName] of [
296
- ['lore', 'lore'],
297
- ['mem0', 'mem0'],
298
- ['claude-mem', 'claude-mem'],
299
- ]) {
300
- for (const dir of [join(home, 'plugins', dirName), join(cwd, '.agents', 'plugins', dirName)]) {
301
- await scanPathRemoval(items, {
302
- platform: 'agy',
303
- tool,
304
- toolName: CONFLICT_TOOLS[tool],
305
- kind: 'plugin',
306
- target: dir,
307
- summary: `插件目录 ${plain(dir)}`,
308
- checkDir: (p) => hasJsonName(join(p, 'plugin.json'), [dirName]),
309
- })
310
- }
311
- }
312
- }
313
-
314
- // ── Gemini CLI (gemini) ──────────────────────────────────────────────────────
315
-
316
- async function scanGeminiConflicts(items, { env, cwd }) {
317
- const home = geminiHome(env)
318
- await scanJsonMcp(items, {
319
- platform: 'gemini',
320
- file: geminiSettingsFile(env),
321
- containerKey: 'mcpServers',
322
- })
323
-
324
- for (const dir of [
325
- join(home, 'extensions', 'lore'),
326
- join(cwd, '.gemini', 'extensions', 'lore'),
327
- ]) {
328
- await scanPathRemoval(items, {
329
- platform: 'gemini',
330
- tool: 'lore',
331
- toolName: 'Lore',
332
- kind: 'plugin',
333
- target: dir,
334
- summary: `Gemini 扩展 ${plain(dir)}`,
335
- checkDir: (p) => hasJsonName(join(p, 'gemini-extension.json'), ['lore']),
336
- })
337
- }
338
- }
339
-
340
- // ── Claude Code (claude-code) ────────────────────────────────────────────────
341
-
342
- const CLAUDE_CONFLICT_PLUGINS = [
343
- { prefix: 'lore@', tool: 'lore', toolName: 'Lore' },
344
- { prefix: 'claude-mem@', tool: 'claude-mem', toolName: 'Claude-Mem' },
345
- ]
346
-
347
- async function scanClaudeConflicts(items, { env, cwd }) {
348
- const home = claudeHome(env)
349
- const settingsFile = join(home, 'settings.json')
350
- const hasClaude = hasCommand('claude', env)
351
-
352
- const removeClaudeMcp = async (name) => {
353
- if (hasClaude) {
354
- await capture('claude', ['mcp', 'remove', name], env, { timeout: 15_000 })
355
- }
356
- }
357
-
358
- // ~/.claude.json、settings.json、项目 .mcp.json 里的 mcpServers
359
- await scanJsonMcp(items, {
360
- platform: 'claude-code',
361
- file: claudeJsonFile(env),
362
- containerKey: 'mcpServers',
363
- onRemove: removeClaudeMcp,
364
- })
365
- await scanJsonMcp(items, {
366
- platform: 'claude-code',
367
- file: settingsFile,
368
- containerKey: 'mcpServers',
369
- onRemove: removeClaudeMcp,
370
- })
371
- await scanJsonMcp(items, {
372
- platform: 'claude-code',
373
- file: join(cwd, '.mcp.json'),
374
- containerKey: 'mcpServers',
375
- onRemove: removeClaudeMcp,
376
- })
377
-
378
- const res = await readJsonSafe(settingsFile)
379
- if (res.ok && res.text !== null) {
380
- const enabled = res.settings?.enabledPlugins
381
- if (enabled && typeof enabled === 'object' && !Array.isArray(enabled)) {
382
- for (const [pluginId, on] of Object.entries(enabled)) {
383
- if (on !== true) continue
384
- const match = CLAUDE_CONFLICT_PLUGINS.find((p) => pluginId.startsWith(p.prefix))
385
- if (!match) continue
386
- items.push({
387
- id: `claude-code:${match.tool}:plugin:${pluginId}`,
388
- platform: 'claude-code',
389
- tool: match.tool,
390
- toolName: match.toolName,
391
- kind: 'plugin',
392
- summary: `插件 ${plain(pluginId)}(${plain(settingsFile)})`,
393
- removable: true,
394
- remove: async ({ noBackupFiles } = {}) => {
395
- if (hasCommand('claude', env)) {
396
- await capture('claude', ['plugins', 'uninstall', pluginId], env, { timeout: 20_000 })
397
- }
398
- const latest = await readSettings(settingsFile)
399
- if (
400
- latest.settings?.enabledPlugins &&
401
- Object.hasOwn(latest.settings.enabledPlugins, pluginId)
402
- ) {
403
- const next = { ...latest.settings }
404
- const nextPlugins = { ...latest.settings.enabledPlugins }
405
- delete nextPlugins[pluginId]
406
- if (Object.keys(nextPlugins).length) next.enabledPlugins = nextPlugins
407
- else delete next.enabledPlugins
408
- await safeWrite(settingsFile, serialize(next, latest.text), latest.text, {
409
- backup: backupAllowed(settingsFile, hasJsonSecret(latest.settings), noBackupFiles),
410
- })
411
- }
412
- return { changed: true, message: `已卸载 Claude Code 插件 ${plain(pluginId)}` }
413
- },
414
- })
415
- }
416
- }
417
-
418
- const envMap = res.settings?.env
419
- if (envMap && typeof envMap === 'object' && !Array.isArray(envMap)) {
420
- const foundKeys = LORE_ENV_KEYS.filter((k) => Object.hasOwn(envMap, k))
421
- if (foundKeys.length) {
422
- items.push({
423
- id: `claude-code:lore:env:${settingsFile}`,
424
- platform: 'claude-code',
425
- tool: 'lore',
426
- toolName: 'Lore',
427
- kind: 'env',
428
- summary: `${plain(settingsFile)} 里的环境变量 ${foundKeys.join('、')}`,
429
- removable: true,
430
- remove: async ({ noBackupFiles } = {}) => {
431
- const latest = await readSettings(settingsFile)
432
- const curEnv = latest.settings?.env
433
- if (!curEnv || typeof curEnv !== 'object' || Array.isArray(curEnv)) {
434
- return { changed: false, message: `${plain(settingsFile)} 里的 env 已不在` }
435
- }
436
- const nextEnv = { ...curEnv }
437
- let changed = false
438
- for (const k of LORE_ENV_KEYS) {
439
- if (Object.hasOwn(nextEnv, k)) {
440
- delete nextEnv[k]
441
- changed = true
442
- }
443
- }
444
- if (!changed) return { changed: false, message: '环境变量已清理' }
445
- const next = { ...latest.settings }
446
- if (Object.keys(nextEnv).length) next.env = nextEnv
447
- else delete next.env
448
- await safeWrite(settingsFile, serialize(next, latest.text), latest.text, {
449
- backup: backupAllowed(settingsFile, true, noBackupFiles),
450
- })
451
- return { changed: true, message: `已从 ${plain(settingsFile)} 移除 Lore 环境变量` }
452
- },
453
- })
454
- }
455
- }
456
- }
457
-
458
- for (const [tool, dirName] of [
459
- ['lore', 'lore'],
460
- ['claude-mem', 'claude-mem'],
461
- ]) {
462
- await scanPathRemoval(items, {
463
- platform: 'claude-code',
464
- tool,
465
- toolName: CONFLICT_TOOLS[tool],
466
- kind: 'plugin',
467
- target: join(home, 'plugins', 'cache', dirName),
468
- summary: `插件缓存 ${plain(join(home, 'plugins', 'cache', dirName))}`,
469
- })
470
- }
471
-
472
- const guidanceFile = join(home, 'lore-guidance.md')
473
- if ((await lstat(guidanceFile).catch(() => null))?.isFile()) {
474
- items.push({
475
- id: `claude-code:lore:guidance:${guidanceFile}`,
476
- platform: 'claude-code',
477
- tool: 'lore',
478
- toolName: 'Lore',
479
- kind: 'guidance',
480
- summary: `指引文件 ${plain(guidanceFile)}`,
481
- removable: true,
482
- remove: async () => {
483
- await rm(guidanceFile, { force: true })
484
- return { changed: true, message: `已删除 ${plain(guidanceFile)}` }
485
- },
486
- })
487
- }
488
-
489
- const claudeMd = join(home, 'CLAUDE.md')
490
- const mdText = await readText(claudeMd).catch(() => null)
491
- if (mdText !== null) {
492
- const lines = mdText.split(/\r?\n/)
493
- const hasImport = lines.some((line) => LORE_GUIDANCE_IMPORT.test(line))
494
- if (hasImport) {
495
- items.push({
496
- id: `claude-code:lore:guidance-import:${claudeMd}`,
497
- platform: 'claude-code',
498
- tool: 'lore',
499
- toolName: 'Lore',
500
- kind: 'guidance',
501
- summary: `${plain(claudeMd)} 里的 lore-guidance.md 导入行`,
502
- removable: true,
503
- remove: async () => {
504
- const latest = await readText(claudeMd)
505
- if (latest === null) return { changed: false, message: `${plain(claudeMd)} 已不在` }
506
- const eol = latest.includes('\r\n') ? '\r\n' : '\n'
507
- const filtered = latest.split(/\r?\n/).filter((line) => !LORE_GUIDANCE_IMPORT.test(line))
508
- while (filtered.length && filtered[0] === '') filtered.shift()
509
- const next = filtered.join(eol)
510
- const normalized =
511
- next && latest.endsWith('\n') && !next.endsWith(eol) ? `${next}${eol}` : next
512
- if (normalized === latest) return { changed: false, message: '导入行已不在' }
513
- await safeWrite(claudeMd, normalized, latest)
514
- return { changed: true, message: `已从 ${plain(claudeMd)} 移除 lore-guidance.md 导入行` }
515
- },
516
- })
517
- } else if (/\blore_(?:boot|search|get_node)\b/i.test(mdText)) {
518
- items.push({
519
- id: `claude-code:lore:guidance-manual:${claudeMd}`,
520
- platform: 'claude-code',
521
- tool: 'lore',
522
- toolName: 'Lore',
523
- kind: 'warning',
524
- summary: `${plain(claudeMd)} 里仍有手写的 Lore 指引(未自动修改)`,
525
- removable: false,
526
- })
527
- }
528
- }
529
- }
530
-
531
- // ── Codex (codex) ────────────────────────────────────────────────────────────
532
-
533
- // 按行扫描 Codex config.toml 里除 kioku 之外的插件段与 MCP 段,复用 codex.mjs 的标题解析
534
- function scanCodexTomlSections(text) {
535
- const eol = text?.includes('\r\n') ? '\r\n' : '\n'
536
- const lines = text ? text.split(/\r?\n/) : []
537
- const sections = []
538
- let current = null
539
- let depth = 0
540
-
541
- const finish = () => {
542
- if (!current) return
543
- while (current.indices.length && /^\s*(#.*)?$/.test(lines[current.indices.at(-1)])) {
544
- current.indices.pop()
545
- }
546
- if (current.indices.length) sections.push(current)
547
- current = null
548
- }
549
-
550
- lines.forEach((line, index) => {
551
- const header = depth === 0 ? headerOf(line) : null
552
- if (header !== null) {
553
- finish()
554
- current = { name: header, indices: [index] }
555
- return
556
- }
557
- depth = Math.max(0, depth + bracketDelta(line))
558
- if (current) current.indices.push(index)
559
- })
560
- finish()
561
-
562
- return { eol, lines, sections }
563
- }
564
-
565
- function removeTomlSections(text, targetPrefixes) {
566
- const { eol, lines, sections } = scanCodexTomlSections(text)
567
- const owned = new Set()
568
- for (const sec of sections) {
569
- if (targetPrefixes.some((prefix) => sec.name === prefix || sec.name.startsWith(`${prefix}.`))) {
570
- for (const idx of sec.indices) owned.add(idx)
571
- }
572
- }
573
- if (!owned.size) return text
574
- const kept = []
575
- lines.forEach((line, index) => {
576
- if (owned.has(index)) return
577
- if (line === '' && owned.has(index - 1) && (kept.at(-1) ?? '') === '') return
578
- kept.push(line)
579
- })
580
- while (kept.length && kept.at(-1) === '') kept.pop()
581
- return kept.length ? `${kept.join(eol)}${eol}` : ''
582
- }
583
-
584
- async function scanCodexConflicts(items, { env }) {
585
- const home = codexHome(env)
586
- const cfgPath = join(home, 'config.toml')
587
- const text = await readText(cfgPath).catch(() => null)
588
- const hasCodex = hasCommand('codex', env)
589
-
590
- if (text !== null) {
591
- const { lines, sections } = scanCodexTomlSections(text)
592
- // 把 [mcp_servers.<name>] 和它的子段(如 [mcp_servers.<name>.http_headers])归成一组
593
- const mcpGroups = new Map()
594
- for (const sec of sections) {
595
- const pluginMatch = /^plugins\.["']?(lore@[^"']+|claude-mem@[^"']+)["']?$/.exec(sec.name)
596
- if (pluginMatch) {
597
- const pluginName = pluginMatch[1]
598
- const tool = pluginName.startsWith('lore@') ? 'lore' : 'claude-mem'
599
- items.push({
600
- id: `codex:${tool}:toml-plugin:${sec.name}`,
601
- platform: 'codex',
602
- tool,
603
- toolName: CONFLICT_TOOLS[tool],
604
- kind: 'plugin',
605
- summary: `[${sec.name}](${plain(cfgPath)})`,
606
- removable: true,
607
- remove: async ({ noBackupFiles } = {}) => {
608
- if (hasCodex && tool === 'lore') {
609
- await capture('codex', ['plugin', 'marketplace', 'remove', 'lore'], env, {
610
- timeout: 15_000,
611
- })
612
- }
613
- const latest = await readText(cfgPath)
614
- if (latest === null) return { changed: false, message: `${plain(cfgPath)} 已不在` }
615
- const next = removeTomlSections(latest, [sec.name])
616
- if (next === latest) return { changed: false, message: `[${sec.name}] 已不在` }
617
- await safeWrite(cfgPath, next, latest, {
618
- backup: backupAllowed(cfgPath, hasTextSecret(latest), noBackupFiles),
619
- })
620
- return { changed: true, message: `已从 ${plain(cfgPath)} 移除 [${sec.name}]` }
621
- },
622
- })
623
- continue
624
- }
625
- const mcpMatch = /^mcp_servers\.("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[^.]+)(?:\.|$)/.exec(
626
- sec.name,
627
- )
628
- if (mcpMatch) {
629
- const serverName = mcpMatch[1].replace(/^["']|["']$/g, '')
630
- if (serverName === 'kioku') continue
631
- const group = mcpGroups.get(serverName) ?? { root: `mcp_servers.${mcpMatch[1]}`, lines: [] }
632
- for (const idx of sec.indices) group.lines.push(lines[idx])
633
- mcpGroups.set(serverName, group)
634
- }
635
- }
636
-
637
- // 行内表或带点键写法的 MCP(如 mcp_servers.lore = ...)按行删不安全,仅提示
638
- for (const inlineName of [
639
- 'lore',
640
- 'lore-skills',
641
- 'mem0',
642
- 'openmemory',
643
- 'supermemory',
644
- 'claude-mem',
645
- ]) {
646
- const escaped = inlineName.replaceAll('-', '\\-')
647
- const inlineRe = new RegExp(
648
- String.raw`^\s*(?:mcp_servers\s*\.\s*["']?${escaped}["']?\s*[.=]|["']?${escaped}["']?\s*=\s*\{)`,
649
- 'm',
650
- )
651
- if (!mcpGroups.has(inlineName) && inlineRe.test(text)) {
652
- const matched = matchMcpTool(inlineName, '')
653
- if (matched) {
654
- items.push({
655
- id: `codex:${matched.tool}:inline:${inlineName}`,
656
- platform: 'codex',
657
- tool: matched.tool,
658
- toolName: matched.toolName,
659
- kind: 'warning',
660
- summary: `${plain(cfgPath)} 里用行内表或带点键定义了 ${inlineName}(未自动修改,需手动删掉)`,
661
- removable: false,
662
- })
663
- }
664
- }
665
- }
666
-
667
- for (const [serverName, group] of mcpGroups) {
668
- const matched = matchMcpTool(serverName, group.lines.join('\n'))
669
- if (!matched) continue
670
- items.push({
671
- id: `codex:${matched.tool}:mcp:${serverName}`,
672
- platform: 'codex',
673
- tool: matched.tool,
674
- toolName: matched.toolName,
675
- kind: matched.removable ? 'mcp' : 'warning',
676
- summary: `[${group.root}](${plain(cfgPath)})`,
677
- removable: matched.removable,
678
- ...(matched.hint ? { hint: matched.hint } : {}),
679
- ...(matched.removable
680
- ? {
681
- remove: async ({ noBackupFiles } = {}) => {
682
- if (hasCodex) {
683
- await capture('codex', ['mcp', 'remove', serverName], env, { timeout: 15_000 })
684
- }
685
- const latest = await readText(cfgPath)
686
- if (latest === null) return { changed: false, message: `${plain(cfgPath)} 已不在` }
687
- const next = removeTomlSections(latest, [group.root, `mcp_servers.${serverName}`])
688
- if (next === latest) return { changed: false, message: `[${group.root}] 已不在` }
689
- await safeWrite(cfgPath, next, latest, {
690
- backup: backupAllowed(cfgPath, hasTextSecret(latest), noBackupFiles),
691
- })
692
- return { changed: true, message: `已从 ${plain(cfgPath)} 移除 [${group.root}]` }
693
- },
694
- }
695
- : {}),
696
- })
697
- }
698
- }
699
-
700
- for (const [sub, desc] of [
701
- [join('plugins', 'lore-local-marketplace'), '本地插件市场'],
702
- [join('plugins', 'cache', 'lore'), '插件缓存'],
703
- [join('hooks', 'lore'), '钩子目录'],
704
- ]) {
705
- await scanPathRemoval(items, {
706
- platform: 'codex',
707
- tool: 'lore',
708
- toolName: 'Lore',
709
- kind: 'plugin',
710
- target: join(home, sub),
711
- summary: `${desc} ${plain(join(home, sub))}`,
712
- })
713
- }
714
-
715
- const hooksFile = join(home, 'hooks.json')
716
- const hooksRes = await readJsonSafe(hooksFile)
717
- if (hooksRes.ok && hooksRes.text !== null && hooksRes.settings?.hooks) {
718
- const hooksObj = hooksRes.settings.hooks
719
- const hasLoreHook =
720
- typeof hooksObj === 'object' &&
721
- !Array.isArray(hooksObj) &&
722
- Object.values(hooksObj).some(
723
- (entries) =>
724
- Array.isArray(entries) &&
725
- entries.some(
726
- (entry) =>
727
- Array.isArray(entry?.hooks) &&
728
- entry.hooks.some((h) => /[/\\]hooks[/\\]lore[/\\]/.test(String(h?.command ?? ''))),
729
- ),
730
- )
731
- if (hasLoreHook) {
732
- items.push({
733
- id: `codex:lore:hooks:${hooksFile}`,
734
- platform: 'codex',
735
- tool: 'lore',
736
- toolName: 'Lore',
737
- kind: 'hook',
738
- summary: `${plain(hooksFile)} 里的 Lore 钩子`,
739
- removable: true,
740
- remove: async () => {
741
- const latest = await readSettings(hooksFile)
742
- const curHooks = latest.settings?.hooks
743
- if (!curHooks || typeof curHooks !== 'object' || Array.isArray(curHooks)) {
744
- return { changed: false, message: `${plain(hooksFile)} 已无 hooks` }
745
- }
746
- const nextHooks = {}
747
- let changed = false
748
- for (const [ev, entries] of Object.entries(curHooks)) {
749
- if (!Array.isArray(entries)) {
750
- nextHooks[ev] = entries
751
- continue
752
- }
753
- const filtered = entries.filter(
754
- (entry) =>
755
- !(
756
- Array.isArray(entry?.hooks) &&
757
- entry.hooks.some((h) => /[/\\]hooks[/\\]lore[/\\]/.test(String(h?.command ?? '')))
758
- ),
759
- )
760
- if (filtered.length < entries.length) changed = true
761
- if (filtered.length) nextHooks[ev] = filtered
762
- }
763
- if (!changed) return { changed: false, message: 'Lore 钩子已不在' }
764
- const next = { ...latest.settings }
765
- if (Object.keys(nextHooks).length) next.hooks = nextHooks
766
- else delete next.hooks
767
- await safeWrite(hooksFile, serialize(next, latest.text), latest.text)
768
- return { changed: true, message: `已从 ${plain(hooksFile)} 移除 Lore 钩子` }
769
- },
770
- })
771
- }
772
- }
773
- }
774
-
775
- // ── OpenCode (opencode) ──────────────────────────────────────────────────────
776
-
777
- async function scanOpenCodeConflicts(items, { env, cwd }) {
778
- const userDir = opencodeHome(env)
779
- const pluginFile = join(userDir, 'plugins', 'lore-memory.js')
780
- const pluginText = await readText(pluginFile).catch(() => null)
781
- if (pluginText !== null) {
782
- if (pluginText.includes(LORE_OPENCODE_MARKER)) {
783
- items.push({
784
- id: `opencode:lore:plugin:${pluginFile}`,
785
- platform: 'opencode',
786
- tool: 'lore',
787
- toolName: 'Lore',
788
- kind: 'plugin',
789
- summary: `插件文件 ${plain(pluginFile)}`,
790
- removable: true,
791
- remove: async () => {
792
- await rm(pluginFile, { force: true })
793
- return { changed: true, message: `已删除 ${plain(pluginFile)}` }
794
- },
795
- })
796
- } else {
797
- items.push({
798
- id: `opencode:lore:warn:${pluginFile}`,
799
- platform: 'opencode',
800
- tool: 'lore',
801
- toolName: 'Lore',
802
- kind: 'warning',
803
- summary: `${plain(pluginFile)} 没有 Lore 托管标记(未自动删除)`,
804
- removable: false,
805
- })
806
- }
807
- }
808
-
809
- for (const cfgFile of [join(userDir, 'opencode.json'), join(cwd, 'opencode.json')]) {
810
- await scanJsonMcp(items, { platform: 'opencode', file: cfgFile, containerKey: 'mcp' })
811
- const res = await readJsonSafe(cfgFile)
812
- if (res.ok && res.text !== null && Array.isArray(res.settings?.plugin)) {
813
- const lorePlugins = res.settings.plugin.filter(
814
- (entry) =>
815
- typeof entry === 'string' && (/lore-memory|@loremem\//i.test(entry) || entry === 'lore'),
816
- )
817
- for (const entry of lorePlugins) {
818
- items.push({
819
- id: `opencode:lore:plugin-entry:${cfgFile}:${entry}`,
820
- platform: 'opencode',
821
- tool: 'lore',
822
- toolName: 'Lore',
823
- kind: 'plugin',
824
- summary: `${plain(cfgFile)} 的 plugin 里的 ${plain(entry)}`,
825
- removable: true,
826
- remove: async ({ noBackupFiles } = {}) => {
827
- const latest = await readSettings(cfgFile)
828
- const list = latest.settings?.plugin
829
- if (!Array.isArray(list) || !list.includes(entry)) {
830
- return { changed: false, message: `${plain(entry)} 已不在` }
831
- }
832
- const nextList = list.filter((x) => x !== entry)
833
- const next = { ...latest.settings }
834
- if (nextList.length) next.plugin = nextList
835
- else delete next.plugin
836
- await safeWrite(cfgFile, serialize(next, latest.text), latest.text, {
837
- backup: backupAllowed(cfgFile, hasJsonSecret(latest.settings), noBackupFiles),
838
- })
839
- return { changed: true, message: `已从 ${plain(cfgFile)} 移除 ${plain(entry)}` }
840
- },
841
- })
842
- }
843
- }
844
- }
845
-
846
- const loreHome = loreHomeOf(env)
847
- const compatState = join(loreHome, 'opencode-compat.json')
848
- if ((await lstat(compatState).catch(() => null))?.isFile()) {
849
- const compatHelper = join(loreHome, 'opencode-compat.py')
850
- const hasHelper = (await lstat(compatHelper).catch(() => null))?.isFile()
851
- if (hasHelper && hasCommand('python3', env)) {
852
- items.push({
853
- id: `opencode:lore:compat:${compatState}`,
854
- platform: 'opencode',
855
- tool: 'lore',
856
- toolName: 'Lore',
857
- kind: 'compat',
858
- summary: `OpenCode 兼容回滚状态 ${plain(compatState)}`,
859
- removable: true,
860
- remove: async () => {
861
- const res = await capture(
862
- 'python3',
863
- [compatHelper, 'uninstall', '--home', homeOf(env), '--lore-home', loreHome],
864
- env,
865
- { timeout: 15_000 },
866
- )
867
- if (!res.ok) throw new KiokuFailure(`恢复 ${plain(compatState)} 失败`)
868
- if (!(await lstat(compatState).catch(() => null))) {
869
- await rm(compatHelper, { force: true }).catch(() => {})
870
- }
871
- return { changed: true, message: '已恢复 OpenCode 兼容配置' }
872
- },
873
- })
874
- } else {
875
- items.push({
876
- id: `opencode:lore:compat-warn:${compatState}`,
877
- platform: 'opencode',
878
- tool: 'lore',
879
- toolName: 'Lore',
880
- kind: 'warning',
881
- summary: `发现 ${plain(compatState)}(缺少 python3 或辅助脚本,请检查 oh-my-openagent 配置)`,
882
- removable: false,
883
- })
884
- }
885
- }
886
- }
887
-
888
- // ── OpenClaw (openclaw) ──────────────────────────────────────────────────────
889
-
890
- const OPENCLAW_MEMORY_PLUGINS = [
891
- { id: 'lore', tool: 'lore', toolName: 'Lore' },
892
- { id: 'mem0', tool: 'mem0', toolName: 'Mem0' },
893
- { id: 'openmemory', tool: 'mem0', toolName: 'Mem0' },
894
- { id: 'supermemory', tool: 'supermemory', toolName: 'Supermemory' },
895
- { id: 'claude-mem', tool: 'claude-mem', toolName: 'Claude-Mem' },
896
- ]
897
-
898
- async function scanOpenclawConflicts(items, { env }) {
899
- const home = openclawHome(env)
900
- const cfgPath = join(home, 'openclaw.json')
901
- const bin = env.KIOKU_OPENCLAW_BIN || 'openclaw'
902
- const res = await readJsonSafe(cfgPath)
903
-
904
- if (res.ok && res.text !== null) {
905
- const entries = res.settings?.plugins?.entries
906
- const slot = res.settings?.plugins?.slots?.memory
907
- for (const plugin of OPENCLAW_MEMORY_PLUGINS) {
908
- const hasEntry =
909
- entries &&
910
- typeof entries === 'object' &&
911
- !Array.isArray(entries) &&
912
- Object.hasOwn(entries, plugin.id)
913
- const hasSlot = slot === plugin.id
914
- if (!hasEntry && !hasSlot) continue
915
- items.push({
916
- id: `openclaw:${plugin.tool}:plugin:${plugin.id}`,
917
- platform: 'openclaw',
918
- tool: plugin.tool,
919
- toolName: plugin.toolName,
920
- kind: 'plugin',
921
- summary: `OpenClaw 插件 ${plugin.id}(${plain(cfgPath)})`,
922
- removable: true,
923
- remove: async ({ noBackupFiles } = {}) => {
924
- if (hasCommand(bin, env)) {
925
- await capture(bin, ['plugins', 'disable', plugin.id], env, { timeout: 30_000 })
926
- await capture(bin, ['plugins', 'uninstall', plugin.id], env, { timeout: 30_000 })
927
- }
928
- const latest = await readSettings(cfgPath)
929
- let changed = false
930
- const next = { ...latest.settings }
931
- if (
932
- next.plugins?.entries &&
933
- typeof next.plugins.entries === 'object' &&
934
- Object.hasOwn(next.plugins.entries, plugin.id)
935
- ) {
936
- const nextEntries = { ...next.plugins.entries }
937
- delete nextEntries[plugin.id]
938
- next.plugins = { ...next.plugins, entries: nextEntries }
939
- changed = true
940
- }
941
- if (next.plugins?.slots?.memory === plugin.id) {
942
- next.plugins = {
943
- ...next.plugins,
944
- slots: { ...next.plugins.slots, memory: 'memory-core' },
945
- }
946
- changed = true
947
- }
948
- if (changed) {
949
- await safeWrite(cfgPath, serialize(next, latest.text), latest.text, {
950
- backup: backupAllowed(cfgPath, hasJsonSecret(latest.settings), noBackupFiles),
951
- })
952
- }
953
- return { changed: true, message: `已清理 OpenClaw 插件 ${plugin.id}` }
954
- },
955
- })
956
- }
957
- }
958
-
959
- await scanPathRemoval(items, {
960
- platform: 'openclaw',
961
- tool: 'lore',
962
- toolName: 'Lore',
963
- kind: 'plugin',
964
- target: join(home, 'extensions', 'lore'),
965
- summary: `扩展目录 ${plain(join(home, 'extensions', 'lore'))}`,
966
- })
967
- }
968
-
969
- // ── pi (pi) ──────────────────────────────────────────────────────────────────
970
-
971
- async function scanPiConflicts(items, { env, cwd }) {
972
- const home = piHome(env)
973
- await scanPathRemoval(items, {
974
- platform: 'pi',
975
- tool: 'lore',
976
- toolName: 'Lore',
977
- kind: 'plugin',
978
- target: join(home, 'extensions', 'lore'),
979
- summary: `pi 扩展 ${plain(join(home, 'extensions', 'lore'))}`,
980
- // pi 扩展可能不是软链而是用户自建目录:只删软链,普通目录保留并警告
981
- checkDir: async () => false,
982
- })
983
-
984
- for (const mcpFile of [join(home, 'mcp.json'), join(cwd, '.pi', 'mcp.json')]) {
985
- await scanJsonMcp(items, { platform: 'pi', file: mcpFile, containerKey: 'mcpServers' })
986
- }
987
-
988
- for (const settingsFile of [join(home, 'settings.json'), join(cwd, '.pi', 'settings.json')]) {
989
- const res = await readJsonSafe(settingsFile)
990
- if (!res.ok || res.text === null || !Array.isArray(res.settings?.packages)) continue
991
- const lorePkgs = res.settings.packages.filter((entry) => {
992
- const source = typeof entry === 'string' ? entry : entry?.source
993
- return typeof source === 'string' && /@loremem\/|\/lore(?:\.git)?(?:$|#)/.test(source)
994
- })
995
- for (const pkg of lorePkgs) {
996
- const source = typeof pkg === 'string' ? pkg : pkg.source
997
- items.push({
998
- id: `pi:lore:package:${settingsFile}:${source}`,
999
- platform: 'pi',
1000
- tool: 'lore',
1001
- toolName: 'Lore',
1002
- kind: 'plugin',
1003
- summary: `${plain(settingsFile)} 的 packages 里的 ${plain(source)}`,
1004
- removable: true,
1005
- remove: async () => {
1006
- const latest = await readSettings(settingsFile)
1007
- const packages = latest.settings?.packages
1008
- if (!Array.isArray(packages)) return { changed: false, message: 'packages 已不在' }
1009
- const filtered = packages.filter((entry) => {
1010
- const s = typeof entry === 'string' ? entry : entry?.source
1011
- return s !== source
1012
- })
1013
- if (filtered.length === packages.length) return { changed: false, message: '已不在' }
1014
- const next = { ...latest.settings }
1015
- if (filtered.length) next.packages = filtered
1016
- else delete next.packages
1017
- await safeWrite(settingsFile, serialize(next, latest.text), latest.text, {
1018
- backup: !hasJsonSecret(latest.settings),
1019
- })
1020
- return { changed: true, message: `已从 ${plain(settingsFile)} 移除 ${plain(source)}` }
1021
- },
1022
- })
1023
- }
1024
- }
1025
- }
1026
-
1027
- // ── DeepSeek Harness (dsh) ───────────────────────────────────────────────────
1028
-
1029
- function removeDshManagedBlock(content) {
1030
- if (!(content.includes(DSH_BEGIN_MARKER) && content.includes(DSH_END_MARKER))) return content
1031
- const start = content.indexOf(DSH_BEGIN_MARKER)
1032
- const end = content.indexOf(DSH_END_MARKER) + DSH_END_MARKER.length
1033
- let remaining = (content.slice(0, start) + content.slice(end))
1034
- .replace(/^\n+/, '')
1035
- .replace(/\n{3,}/g, '\n\n')
1036
- const meaningful = remaining
1037
- .split(/\r?\n/)
1038
- .map((line) => line.trim())
1039
- .filter((line) => line.length > 0 && !line.startsWith('#'))
1040
- if (meaningful.length === 0) {
1041
- const comments = remaining
1042
- .split(/\r?\n/)
1043
- .filter((line) => line.trim().startsWith('#') || line.trim() === '')
1044
- .join('\n')
1045
- .replace(/\n+$/, '\n')
1046
- return `${comments}[]\n`
1047
- }
1048
- return `${remaining.replace(/\s+$/, '')}\n`
1049
- }
1050
-
1051
- async function scanDshConflicts(items, { env }) {
1052
- const file = join(dshHome(env), 'cordis.patch.yml')
1053
- const text = await readText(file).catch(() => null)
1054
- if (text === null) return
1055
-
1056
- if (text.includes(DSH_BEGIN_MARKER) && text.includes(DSH_END_MARKER)) {
1057
- items.push({
1058
- id: `dsh:lore:patch:${file}`,
1059
- platform: 'dsh',
1060
- tool: 'lore',
1061
- toolName: 'Lore',
1062
- kind: 'plugin',
1063
- summary: `${plain(file)} 里的 Lore 托管块`,
1064
- removable: true,
1065
- remove: async () => {
1066
- const latest = await readText(file)
1067
- if (latest === null) return { changed: false, message: `${plain(file)} 已不在` }
1068
- const next = removeDshManagedBlock(latest)
1069
- if (next === latest) return { changed: false, message: 'Lore 托管块已不在' }
1070
- await safeWrite(file, next, latest, { backup: !hasTextSecret(latest) })
1071
- return { changed: true, message: `已从 ${plain(file)} 移除 Lore 托管块` }
1072
- },
1073
- })
1074
- }
1075
-
1076
- // 非托管区块里若写了其他记忆 MCP 的 serverName,仅提示不改 YAML
1077
- const stripped = removeDshManagedBlock(text)
1078
- for (const match of stripped.matchAll(/^\s*serverName:\s*["']?([A-Za-z0-9_-]+)["']?/gm)) {
1079
- const matched = matchMcpTool(match[1], '')
1080
- if (!matched) continue
1081
- items.push({
1082
- id: `dsh:${matched.tool}:warn:${file}:${match[1]}`,
1083
- platform: 'dsh',
1084
- tool: matched.tool,
1085
- toolName: matched.toolName,
1086
- kind: 'warning',
1087
- summary: `${plain(file)} 里有非托管的 serverName: ${match[1]}(未自动修改)`,
1088
- removable: false,
1089
- })
1090
- }
1091
- }
1092
-
1093
- // ── Hermes (hermes) ──────────────────────────────────────────────────────────
1094
-
1095
- async function hasHermesLoreFiles(dir) {
1096
- const yaml = await readText(join(dir, 'plugin.yaml')).catch(() => null)
1097
- if (yaml && /\bname:\s*["']?lore/i.test(yaml)) return true
1098
- const initPy = await readText(join(dir, '__init__.py')).catch(() => null)
1099
- return Boolean(initPy && /\bLORE_(?:BASE_URL|API_TOKEN)\b/.test(initPy))
1100
- }
1101
-
1102
- async function scanHermesConflicts(items, { env }) {
1103
- const home = hermesHome(env)
1104
- for (const sub of ['skills', 'plugins']) {
1105
- await scanPathRemoval(items, {
1106
- platform: 'hermes',
1107
- tool: 'lore',
1108
- toolName: 'Lore',
1109
- kind: 'plugin',
1110
- target: join(home, sub, 'lore_memory'),
1111
- summary: `Hermes ${sub === 'skills' ? '技能' : '插件'} ${plain(join(home, sub, 'lore_memory'))}`,
1112
- checkDir: hasHermesLoreFiles,
1113
- })
1114
- }
1115
-
1116
- const envFile = join(home, '.env')
1117
- const envText = await readText(envFile).catch(() => null)
1118
- if (envText !== null) {
1119
- const presentKeys = LORE_ENV_KEYS.filter((key) =>
1120
- new RegExp(String.raw`^\s*(?:export\s+)?${key}\s*=`, 'm').test(envText),
1121
- )
1122
- if (presentKeys.length) {
1123
- items.push({
1124
- id: `hermes:lore:env:${envFile}`,
1125
- platform: 'hermes',
1126
- tool: 'lore',
1127
- toolName: 'Lore',
1128
- kind: 'env',
1129
- summary: `${plain(envFile)} 里的 ${presentKeys.join('、')}`,
1130
- removable: true,
1131
- remove: async () => {
1132
- const latest = await readText(envFile)
1133
- if (latest === null) return { changed: false, message: `${plain(envFile)} 已不在` }
1134
- const removals = Object.fromEntries(LORE_ENV_KEYS.map((k) => [k, null]))
1135
- const next = withEnv(latest, removals)
1136
- if (next === latest) return { changed: false, message: '环境变量已清理' }
1137
- await safeWrite(envFile, next, latest, { backup: false })
1138
- return { changed: true, message: `已从 ${plain(envFile)} 移除 Lore 环境变量` }
1139
- },
1140
- })
1141
- }
1142
- }
1143
-
1144
- const bin = env.KIOKU_HERMES_BIN || 'hermes'
1145
- const hasHome = Boolean((await lstat(home).catch(() => null))?.isDirectory())
1146
- if (hasHome && hasCommand(bin, env)) {
1147
- const res = await capture(bin, ['config', 'get', 'memory.provider'], env, { timeout: 15_000 })
1148
- const provider = res.ok ? res.stdout.trim().split(/\r?\n/).at(-1)?.trim() : ''
1149
- if (provider && /^(?:lore|lore_memory)$/i.test(provider)) {
1150
- items.push({
1151
- id: `hermes:lore:provider:${provider}`,
1152
- platform: 'hermes',
1153
- tool: 'lore',
1154
- toolName: 'Lore',
1155
- kind: 'provider',
1156
- summary: `Hermes 当前记忆 provider 为 ${plain(provider)}`,
1157
- removable: true,
1158
- remove: async () => {
1159
- const setRes = await capture(bin, ['config', 'set', 'memory.provider', ''], env, {
1160
- timeout: 15_000,
1161
- })
1162
- if (!setRes.ok) throw new KiokuFailure('清除 Hermes 的 memory.provider 没有成功')
1163
- return {
1164
- changed: true,
1165
- message: `已清除 Hermes 的 memory.provider(原为 ${plain(provider)})`,
1166
- }
1167
- },
1168
- })
1169
- }
1170
- } else if (hasHome) {
1171
- const cfgYaml = await readText(join(home, 'config.yaml')).catch(() => null)
1172
- if (cfgYaml && /^\s*provider:\s*["']?lore(?:_memory)?["']?\s*(?:#.*)?$/m.test(cfgYaml)) {
1173
- items.push({
1174
- id: `hermes:lore:provider-warn:${home}`,
1175
- platform: 'hermes',
1176
- tool: 'lore',
1177
- toolName: 'Lore',
1178
- kind: 'warning',
1179
- summary: `${plain(join(home, 'config.yaml'))} 里的 provider 为 lore(缺少 hermes 命令,需手动清除或重新接入)`,
1180
- removable: false,
1181
- })
1182
- }
1183
- }
1184
- }
1185
-
1186
- const SCANNERS = {
1187
- agy: scanAgyConflicts,
1188
- gemini: scanGeminiConflicts,
1189
- 'claude-code': scanClaudeConflicts,
1190
- codex: scanCodexConflicts,
1191
- opencode: scanOpenCodeConflicts,
1192
- openclaw: scanOpenclawConflicts,
1193
- pi: scanPiConflicts,
1194
- dsh: scanDshConflicts,
1195
- hermes: scanHermesConflicts,
1196
- }
1197
-
1198
- // 只读扫描单个平台的冲突记忆工具,返回冲突项数组
1199
- export async function scanConflicts(platformId, { env = process.env, cwd = process.cwd() } = {}) {
1200
- const fn = SCANNERS[platformId]
1201
- if (!fn) return []
1202
- const items = []
1203
- await fn(items, { env, cwd })
1204
- return items
1205
- }
1206
-
1207
- // 扫描多个平台(默认全部)
1208
- export async function scanAllConflicts(
1209
- platformIds = Object.keys(SCANNERS),
1210
- { env = process.env, cwd = process.cwd() } = {},
1211
- ) {
1212
- const lists = await Promise.all(platformIds.map((id) => scanConflicts(id, { env, cwd })))
1213
- return lists.flat()
1214
- }
1215
-
1216
- // 逐项执行清理,返回结果数组;单条失败不中断其余项
1217
- export async function removeConflicts(items, { env = process.env, cwd = process.cwd(), out } = {}) {
1218
- const results = []
1219
- const noBackupFiles = new Set()
1220
- for (const item of items) {
1221
- if (!item.removable || typeof item.remove !== 'function') {
1222
- results.push({ item, ok: false, skipped: true, message: item.summary })
1223
- continue
1224
- }
1225
- try {
1226
- const res = await item.remove({ env, cwd, noBackupFiles })
1227
- out?.write(`✓ ${res.message}\n`)
1228
- results.push({ item, ok: true, changed: res.changed, message: res.message })
1229
- } catch (err) {
1230
- const message = err instanceof KiokuFailure ? err.message : `清理失败:${item.summary}`
1231
- out?.write(`✗ ${message}\n`)
1232
- results.push({ item, ok: false, message })
1233
- }
1234
- }
1235
- return results
1236
- }
1237
-
1238
- export function conflictToolsText(items) {
1239
- return [...new Set(items.map((item) => item.toolName))].join('、')
1240
- }
1241
-
1242
- export function formatConflicts(items, platforms) {
1243
- return items.map((item) => {
1244
- const label = platforms?.[item.platform]?.name ?? item.platform
1245
- const prefix = item.removable ? ' 清理' : ' 提示'
1246
- const hint = item.hint ? `(${item.hint})` : ''
1247
- return `${prefix} [${label}] ${item.toolName}:${item.summary}${hint}`
1248
- })
1249
- }
1250
-
1251
- // 接入或登录前检查平台上的冲突:有可清理的冲突时,--dry-run 只预览,--remove-conflicts 或终端确认后清理,
1252
- // 非终端且未传 --remove-conflicts 时阻断
1253
- export async function ensureNoConflicts(
1254
- platformId,
1255
- platformName,
1256
- {
1257
- env = process.env,
1258
- cwd = process.cwd(),
1259
- out = process.stdout,
1260
- stdin = process.stdin,
1261
- remove = false,
1262
- dryRun = false,
1263
- } = {},
1264
- ) {
1265
- const items = await scanConflicts(platformId, { env, cwd })
1266
- const warnings = items.filter((item) => !item.removable)
1267
- for (const w of warnings) {
1268
- const hint = w.hint ? `(${w.hint})` : ''
1269
- out.write(`! ${w.toolName}:${w.summary}${hint}\n`)
1270
- }
1271
- const removable = items.filter((item) => item.removable)
1272
- if (!removable.length) return 'ok'
1273
-
1274
- out.write(`发现冲突的记忆工具(${platformName}):\n`)
1275
- out.write(`${formatConflicts(removable).join('\n')}\n`)
1276
-
1277
- if (dryRun) {
1278
- out.write(
1279
- remove
1280
- ? `将先清理以上 ${removable.length} 项冲突\n`
1281
- : `注意:存在冲突,写入前需先清理(运行 kioku clean ${platformId},或加 --remove-conflicts)\n`,
1282
- )
1283
- return 'ok'
1284
- }
1285
-
1286
- if (!remove) {
1287
- if (!stdin?.isTTY) {
1288
- throw new KiokuFailure(
1289
- `${platformName} 存在冲突的记忆工具,未继续:先运行 kioku clean ${platformId},或加上 --remove-conflicts`,
1290
- )
1291
- }
1292
- if (!(await confirm('先卸载这些冲突再继续?[y/N] ', { stdin, out }))) {
1293
- out.write('没有写入\n')
1294
- return 'cancelled'
1295
- }
1296
- }
1297
-
1298
- const results = await removeConflicts(removable, { env, cwd, out })
1299
- if (results.some((r) => !r.ok)) {
1300
- throw new KiokuFailure(`清理 ${platformName} 上的冲突没有全部成功,已停下`)
1301
- }
1302
- return 'cleaned'
1303
- }