@kioku-memory/plugin-opencode 0.0.0-stage → 0.1.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/agy.mjs ADDED
@@ -0,0 +1,181 @@
1
+ // Antigravity (agy) 这个平台的 kioku setup 与 kioku doctor。
2
+ // agy 没有自带的长期记忆要停用,setup 做两件事:
3
+ // 1. 把服务地址与访问密钥写进本机文件(只给本人读写,插件的 hooks.json 钩子读它);
4
+ // 2. 在 ~/.gemini/config/mcp_config.json 里写入 mcpServers.kioku(Streamable HTTP)
5
+
6
+ import { stat } from 'node:fs/promises'
7
+ import { homedir } from 'node:os'
8
+ import { join } from 'node:path'
9
+
10
+ import { readSettings, safeWrite, serialize } from './files.mjs'
11
+ import { KiokuFailure } from './http.mjs'
12
+ import { profileFile, readProfile, removeProfile, writeProfile } from './profile.mjs'
13
+ import { resolveTarget } from './target.mjs'
14
+
15
+ export function agyHome(env) {
16
+ if (env.AGY_HOME) return env.AGY_HOME
17
+ return join(env.HOME || homedir(), '.gemini', 'config')
18
+ }
19
+
20
+ export function agyMcpFile(env) {
21
+ return join(agyHome(env), 'mcp_config.json')
22
+ }
23
+
24
+ function checkMcpShape(settings, file) {
25
+ if (
26
+ settings.mcpServers !== undefined &&
27
+ (settings.mcpServers === null ||
28
+ typeof settings.mcpServers !== 'object' ||
29
+ Array.isArray(settings.mcpServers))
30
+ ) {
31
+ throw new KiokuFailure(`${file} 里的 mcpServers 不是对象,没有改动它`)
32
+ }
33
+ }
34
+
35
+ function mcpEntry(url, key) {
36
+ return {
37
+ url: `${url}/v1/mcp`,
38
+ headers: { Authorization: `Bearer ${key}` },
39
+ }
40
+ }
41
+
42
+ function sameMcp(existing, wanted) {
43
+ return (
44
+ existing?.url === wanted.url &&
45
+ existing?.headers?.Authorization === wanted.headers.Authorization
46
+ )
47
+ }
48
+
49
+ function hasStoredKey(settings) {
50
+ return Boolean(settings?.mcpServers?.kioku?.headers?.Authorization)
51
+ }
52
+
53
+ function buildMcp(settings, { url, key, undo }) {
54
+ const next = { ...settings }
55
+ if (undo) {
56
+ if (
57
+ settings.mcpServers &&
58
+ typeof settings.mcpServers === 'object' &&
59
+ Object.hasOwn(settings.mcpServers, 'kioku')
60
+ ) {
61
+ const mcp = { ...settings.mcpServers }
62
+ delete mcp.kioku
63
+ if (Object.keys(mcp).length) next.mcpServers = mcp
64
+ else delete next.mcpServers
65
+ }
66
+ return next
67
+ }
68
+ next.mcpServers = { ...(settings.mcpServers ?? {}), kioku: mcpEntry(url, key) }
69
+ return next
70
+ }
71
+
72
+ async function pluginInstalled(env, cwd) {
73
+ for (const file of [
74
+ join(agyHome(env), 'plugins', 'kioku', 'plugin.json'),
75
+ join(cwd, '.agents', 'plugins', 'kioku', 'plugin.json'),
76
+ ]) {
77
+ if ((await stat(file).catch(() => null))?.isFile()) return true
78
+ }
79
+ return false
80
+ }
81
+
82
+ export async function preflightAgy({ env }) {
83
+ const file = agyMcpFile(env)
84
+ const { settings } = await readSettings(file)
85
+ checkMcpShape(settings, file)
86
+ }
87
+
88
+ export async function setupAgy(options, io) {
89
+ const { env, out, cwd } = io
90
+ const profile = profileFile('agy', env)
91
+ const file = agyMcpFile(env)
92
+
93
+ if (options.undo) {
94
+ const { settings, text } = await readSettings(file)
95
+ checkMcpShape(settings, file)
96
+ const next = buildMcp(settings, { undo: true })
97
+ if (JSON.stringify(settings) === JSON.stringify(next)) {
98
+ if (text !== null) out.write(`${file} 不用改\n`)
99
+ } else {
100
+ out.write(`${file}:去掉 mcpServers.kioku\n`)
101
+ if (!options.dryRun) {
102
+ // 原文件里带着访问密钥时不留备份
103
+ await safeWrite(file, serialize(next, text), text, { backup: !hasStoredKey(settings) })
104
+ }
105
+ }
106
+
107
+ if (options.dryRun) out.write(`${profile}:删掉\n没有写入(--dry-run)\n`)
108
+ else if (await removeProfile('agy', env)) out.write(`已删掉 ${profile}\n`)
109
+ else out.write(`${profile} 本来就没有\n`)
110
+ return 0
111
+ }
112
+
113
+ await preflightAgy({ env })
114
+ const { url, key, saved } = await resolveTarget({ id: 'agy', name: 'Antigravity' }, options, {
115
+ ...io,
116
+ beforeLogin: () => preflightAgy({ env }),
117
+ })
118
+
119
+ const { settings, text } = await readSettings(file)
120
+ checkMcpShape(settings, file)
121
+ const next = buildMcp(settings, { url, key, undo: false })
122
+ const sameProfile = Boolean(saved && saved.url === url && saved.key === key)
123
+ const sameFile = JSON.stringify(settings) === JSON.stringify(next)
124
+
125
+ if (sameProfile) out.write(`${profile} 不用改\n`)
126
+ else out.write(`${profile}:写入服务地址与访问密钥(只给本人读写)\n`)
127
+
128
+ if (sameFile) out.write(`${file} 不用改\n`)
129
+ else out.write(`${file}:配置 mcpServers.kioku\n`)
130
+
131
+ if (options.dryRun) {
132
+ out.write('没有写入(--dry-run)\n')
133
+ return 0
134
+ }
135
+
136
+ if (!sameProfile) await writeProfile('agy', { url, key }, env)
137
+ if (!sameFile) {
138
+ const backedUp = await safeWrite(file, serialize(next, text), text, {
139
+ backup: !hasStoredKey(settings),
140
+ })
141
+ if (backedUp) out.write(`原配置已备份到 ${file}.kioku-backup\n`)
142
+ }
143
+ out.write('Antigravity 已配好,新开会话生效。\n')
144
+ if (!(await pluginInstalled(env, cwd)) && io.hints !== false) {
145
+ out.write(
146
+ `接下来安装插件以启用生命周期钩子:cp -r <仓库目录>/plugins/agy ${join(agyHome(env), 'plugins', 'kioku')}\n`,
147
+ )
148
+ }
149
+ return 0
150
+ }
151
+
152
+ export async function inspectAgy({ env, cwd }, { ok, warn }) {
153
+ const profile = await readProfile('agy', env).catch(() => null)
154
+ if (!profile) {
155
+ warn('没有 kioku setup agy 写下的地址与访问密钥,插件钩子不会生效:运行 kioku setup agy')
156
+ }
157
+
158
+ const file = agyMcpFile(env)
159
+ const { settings } = await readSettings(file)
160
+ const entry = settings?.mcpServers?.kioku
161
+ if (!entry) {
162
+ warn(`${file} 里没有 mcpServers.kioku:运行 kioku setup agy`)
163
+ } else if (!entry.url) {
164
+ warn(`${file} 里的 mcpServers.kioku 缺少 url:运行 kioku setup agy`)
165
+ } else if (profile && !sameMcp(entry, mcpEntry(profile.url, profile.key))) {
166
+ warn(`${file} 里的 mcpServers.kioku 与当前地址或访问密钥不一致:运行 kioku setup agy`)
167
+ } else {
168
+ ok(`${file} 里的 mcpServers.kioku 已配好`)
169
+ }
170
+
171
+ if (await pluginInstalled(env, cwd)) ok('Antigravity 已安装 kioku 插件')
172
+ else
173
+ warn(
174
+ `Antigravity 未安装 kioku 插件:将 plugins/agy 放到 ${join(agyHome(env), 'plugins', 'kioku')}`,
175
+ )
176
+ ok('Antigravity 没有自带的长期记忆要停用')
177
+ }
178
+
179
+ export async function statusAgy({ env, cwd }) {
180
+ return { plugin: await pluginInstalled(env, cwd), memory: 'none' }
181
+ }
package/lib/api.mjs ADDED
@@ -0,0 +1,38 @@
1
+ // kioku 命令向 Kioku 发的核对请求
2
+
3
+ import { fetchFailure, isRedirect, KiokuFailure, redirectError } from './http.mjs'
4
+
5
+ const TIMEOUT = 8000
6
+
7
+ // 服务端明说访问密钥不能用(401):和连不上、响应不对分开,向导据此标「已失效」
8
+ export class KeyRejected extends KiokuFailure {}
9
+
10
+ // 这个访问密钥对应的应用与权限;连不上、跳转、访问密钥无效、响应不对都以 KiokuFailure 抛出
11
+ export async function whoami({ url, key }) {
12
+ let res
13
+ let data
14
+ try {
15
+ res = await fetch(`${url}/v1/whoami`, {
16
+ headers: { authorization: `Bearer ${key}` },
17
+ // 不跟着跳转走:访问密钥只发给配置的地址
18
+ redirect: 'manual',
19
+ signal: AbortSignal.timeout(TIMEOUT),
20
+ })
21
+ data = await res.json().catch(() => null)
22
+ } catch (err) {
23
+ throw new KiokuFailure(fetchFailure(err, TIMEOUT))
24
+ }
25
+ if (isRedirect(res.status)) {
26
+ throw new KiokuFailure(redirectError(res.status, res.headers.get('location'), url))
27
+ }
28
+ if (res.status === 401) throw new KeyRejected('访问密钥无效或已吊销')
29
+ if (!res.ok) throw new KiokuFailure(`Kioku 返回 HTTP ${res.status}`)
30
+ if (
31
+ typeof data?.app?.runtimeFamily !== 'string' ||
32
+ data.scopes === null ||
33
+ typeof data.scopes !== 'object'
34
+ ) {
35
+ throw new KiokuFailure('Kioku 的响应格式不对')
36
+ }
37
+ return data
38
+ }
package/lib/clean.mjs ADDED
@@ -0,0 +1,96 @@
1
+ // kioku clean:检测并卸载与 Kioku 冲突的记忆工具(Lore 及常见记忆 MCP)。
2
+ // 默认先列计划并询问确认(非终端运行需传 -y/--yes);只清理平台侧配置,不删服务端数据目录。
3
+
4
+ import { CONFLICT_TOOLS, formatConflicts, removeConflicts, scanAllConflicts } from './conflicts.mjs'
5
+ import { confirm } from './import.mjs'
6
+ import { KiokuFailure } from './http.mjs'
7
+ import { platformNames, PLATFORMS } from './platforms.mjs'
8
+ import { UsageError } from './usage.mjs'
9
+
10
+ const CLEANABLE_TOOLS = Object.keys(CONFLICT_TOOLS).filter((id) => id !== 'unknown-memory')
11
+
12
+ export const CLEAN_USAGE = `用法:kioku clean [平台] [--tool <工具>] [--dry-run] [-y|--yes]
13
+
14
+ 检测并卸载与 Kioku 冲突的记忆工具(Lore 及常见记忆 MCP)。
15
+ 只清理目标平台上的接入配置或插件挂载,不删服务端数据目录。
16
+
17
+ [平台] ${platformNames()};不写时扫描全部平台
18
+ --tool <工具> 只清理指定工具:${CLEANABLE_TOOLS.join('、')}
19
+ --dry-run 只列出发现的冲突,不修改文件
20
+ -y, --yes 不问,直接清理(不在终端里运行时要带上)
21
+ `
22
+
23
+ export function parseCleanArgs(argv) {
24
+ const options = { platform: null, tool: null, dryRun: false, yes: false }
25
+ for (let i = 0; i < argv.length; i++) {
26
+ const arg = argv[i]
27
+ if (arg === '--dry-run') options.dryRun = true
28
+ else if (arg === '-y' || arg === '--yes') options.yes = true
29
+ else if (arg === '--tool') {
30
+ const value = argv[++i]
31
+ if (!value) throw new UsageError('--tool 后面要写工具名')
32
+ if (!CLEANABLE_TOOLS.includes(value)) {
33
+ throw new UsageError(`不认识的工具 ${value},可以用的:${CLEANABLE_TOOLS.join('、')}`)
34
+ }
35
+ options.tool = value
36
+ } else if (arg.startsWith('-')) {
37
+ throw new UsageError(`不认识的选项 ${arg}`)
38
+ } else if (options.platform !== null) {
39
+ throw new UsageError('最多写一个平台')
40
+ } else {
41
+ if (!Object.hasOwn(PLATFORMS, arg)) {
42
+ throw new UsageError(`不认识的平台 ${arg},可以用的:${platformNames()}`)
43
+ }
44
+ options.platform = arg
45
+ }
46
+ }
47
+ return options
48
+ }
49
+
50
+ export async function clean(
51
+ argv,
52
+ { env = process.env, out = process.stdout, cwd = process.cwd(), stdin = process.stdin } = {},
53
+ ) {
54
+ const options = parseCleanArgs(argv)
55
+ const targetIds = options.platform ? [options.platform] : Object.keys(PLATFORMS)
56
+ const all = await scanAllConflicts(targetIds, { env, cwd })
57
+ const items = options.tool ? all.filter((item) => item.tool === options.tool) : all
58
+
59
+ if (!items.length) {
60
+ out.write(
61
+ options.platform
62
+ ? `${PLATFORMS[options.platform].name}:没有发现冲突的记忆工具\n`
63
+ : '没有发现冲突的记忆工具\n',
64
+ )
65
+ return 0
66
+ }
67
+
68
+ out.write('发现以下冲突或疑似项:\n')
69
+ out.write(`${formatConflicts(items, PLATFORMS).join('\n')}\n`)
70
+
71
+ const removable = items.filter((item) => item.removable)
72
+ if (options.dryRun) {
73
+ out.write('没有改动(--dry-run)\n')
74
+ return 0
75
+ }
76
+ if (!removable.length) {
77
+ out.write('没有可自动卸载的项,请按上面的提示手动处理。\n')
78
+ return 0
79
+ }
80
+
81
+ if (!options.yes) {
82
+ if (!stdin.isTTY) {
83
+ throw new KiokuFailure('不在终端里运行时要带 --yes 才清理;先用 --dry-run 看计划')
84
+ }
85
+ if (!(await confirm(`清理以上 ${removable.length} 项冲突?[y/N] `, { stdin, out }))) {
86
+ out.write('没有改动\n')
87
+ return 0
88
+ }
89
+ }
90
+
91
+ out.write('\n')
92
+ const results = await removeConflicts(removable, { env, cwd, out })
93
+ const failed = results.some((r) => !r.ok)
94
+ if (!failed) out.write('清理完成,重启对应平台后生效。\n')
95
+ return failed ? 1 : 0
96
+ }
package/lib/codex.mjs ADDED
@@ -0,0 +1,320 @@
1
+ // Codex 这个平台的 kioku setup 与 kioku doctor。
2
+ // Codex 的插件没有自己的配置项,MCP 服务的地址也只能写在用户的 config.toml 里,所以 setup 做三件事:
3
+ // 把服务地址与访问密钥写进本机的文件(钩子读它)、在 config.toml 里加上 Kioku 的 MCP 服务、关掉 Codex 自带的 Memories。
4
+ // config.toml 只按行改:不解析整份 TOML,只认段的标题与要改的那几行。名叫 kioku 的 MCP 服务
5
+ // ([mcp_servers.kioku] 与它的子段)整个归 kioku setup 管。不用标记行圈范围:Codex 自己也会重写这个文件,
6
+ // 注释会被它挪到别的段后面
7
+
8
+ import { readdir, rm } from 'node:fs/promises'
9
+ import { homedir } from 'node:os'
10
+ import { join } from 'node:path'
11
+
12
+ import { readText, safeWrite } from './files.mjs'
13
+ import { KiokuFailure } from './http.mjs'
14
+ import { profileDir, profileFile, readProfile, removeProfile, writeProfile } from './profile.mjs'
15
+ import { resolveTarget } from './target.mjs'
16
+ import { plain as plainText, shownUrl } from './text.mjs'
17
+
18
+ const SERVER = 'mcp_servers.kioku'
19
+ const MARKETPLACE = 'lonelyman0108/kioku-plugins'
20
+
21
+ export function codexHome(env) {
22
+ return env.CODEX_HOME || join(homedir(), '.codex')
23
+ }
24
+
25
+ // TOML 的基本字符串:反斜杠与双引号要转义。地址与访问密钥都只有可见的 ASCII 字符
26
+ function quoted(value) {
27
+ return `"${value.replaceAll('\\', '\\\\').replaceAll('"', '\\"')}"`
28
+ }
29
+
30
+ function unquoted(value) {
31
+ return (value ?? '').replace(/\\(["\\])/g, '$1')
32
+ }
33
+
34
+ // 写进 config.toml 的那几行
35
+ function blockOf({ url, key }) {
36
+ return [
37
+ `[${SERVER}]`,
38
+ `url = ${quoted(`${url}/v1/mcp`)}`,
39
+ '',
40
+ `[${SERVER}.http_headers]`,
41
+ `Authorization = ${quoted(`Bearer ${key}`)}`,
42
+ ]
43
+ }
44
+
45
+ // 标题里的一段名字:不带引号的,或者带引号的
46
+ const KEY_PART = String.raw`(?:[A-Za-z0-9_-]+|"[^"]*"|'[^']*')`
47
+ const HEADER = new RegExp(
48
+ String.raw`^\s*\[\[?\s*(${KEY_PART}(?:\s*\.\s*${KEY_PART})*)\s*\]\]?\s*(#.*)?$`,
49
+ )
50
+
51
+ // 段的标题:[a.b] 或 [[a.b]],返回里面的名字;不是标题时为 null。
52
+ // 名字规整成一种写法再比:点两边的空白去掉,只含普通字符的那一段去掉引号
53
+ export function headerOf(line) {
54
+ const name = HEADER.exec(line)?.[1]
55
+ if (name === undefined) return null
56
+ return name
57
+ .replace(/\s*\.\s*/g, '.')
58
+ .replace(/"([A-Za-z0-9_-]+)"|'([A-Za-z0-9_-]+)'/g, (_, a, b) => a ?? b)
59
+ }
60
+
61
+ // 这一行让没有合上的方括号多了几层:多行的数组里,单独成行的 [1, 2] 不是标题。引号里的不算
62
+ export function bracketDelta(line) {
63
+ const bare = line.replace(/"(?:[^"\\]|\\.)*"|'[^']*'/g, '').replace(/#.*$/, '')
64
+ return (bare.match(/\[/g)?.length ?? 0) - (bare.match(/\]/g)?.length ?? 0)
65
+ }
66
+
67
+ // 把 config.toml 按行读成要用的几样:
68
+ // - owned:kioku 的 MCP 服务占了哪些行
69
+ // - unsupported:这个服务用按行认不出范围的写法定义了(行内表、带点的键),不能再加一段同名的
70
+ // - memories:Memories 的开关写在哪一行;memoriesUnknown:features 用认不出的写法写了
71
+ // - plugin:kioku 插件启用没有
72
+ export function scanConfig(text) {
73
+ const eol = text?.includes('\r\n') ? '\r\n' : '\n'
74
+ const lines = text ? text.split(/\r?\n/) : []
75
+ const found = {
76
+ eol,
77
+ lines,
78
+ owned: [],
79
+ unsupported: false,
80
+ memories: null,
81
+ memoriesUnknown: false,
82
+ plugin: false,
83
+ }
84
+ let section = ''
85
+ let depth = 0
86
+ lines.forEach((line, index) => {
87
+ const header = depth === 0 ? headerOf(line) : null
88
+ if (header !== null) section = header
89
+ else depth = Math.max(0, depth + bracketDelta(line))
90
+ if (section === SERVER || section.startsWith(`${SERVER}.`)) {
91
+ found.owned.push(index)
92
+ return
93
+ }
94
+ if (header !== null) return
95
+ // 这个服务的别的写法:最前面的 mcp_servers.kioku…、mcp_servers = { kioku… },或者 [mcp_servers] 段里的 kioku
96
+ const quotedName = String.raw`["']?kioku["']?`
97
+ if (
98
+ (section === '' &&
99
+ new RegExp(String.raw`^\s*mcp_servers\s*(\.\s*${quotedName}\s*[.=]|=.*\bkioku\b)`).test(
100
+ line,
101
+ )) ||
102
+ (section === 'mcp_servers' && new RegExp(String.raw`^\s*${quotedName}\s*[.=]`).test(line))
103
+ ) {
104
+ found.unsupported = true
105
+ }
106
+ // Memories 的开关:[features] 段里的 memories,或者写在最前面的 features.memories
107
+ const name = String.raw`["']?memories["']?`
108
+ const key =
109
+ section === 'features' ? name : section === '' ? String.raw`features\s*\.\s*${name}` : null
110
+ const flag = key && new RegExp(String.raw`^(\s*${key}\s*=\s*)(true|false)\b(.*)$`).exec(line)
111
+ if (flag) found.memories = { index, value: flag[2] === 'true', parts: flag }
112
+ // features 写成行内表时认不出里面的开关
113
+ if (section === '' && /^\s*features\s*=/.test(line)) found.memoriesUnknown = true
114
+ // 插件:[plugins."kioku@<市场>"] 段里的 enabled = true
115
+ if (/^plugins\.["']kioku@[^"']+["']$/.test(section) && /^\s*enabled\s*=\s*true\b/.test(line)) {
116
+ found.plugin = true
117
+ }
118
+ })
119
+ // 这一段后面的空行与注释不算它的(注释多半是写给下一段的):去掉这一段时不连带去掉
120
+ while (found.owned.length && /^\s*(#.*)?$/.test(lines[found.owned.at(-1)])) found.owned.pop()
121
+ return found
122
+ }
123
+
124
+ // kioku 的 MCP 服务现在写的地址与访问密钥;没有这个服务时为 null,有但认不出写法的那一项为空
125
+ export function blockValues(found) {
126
+ if (!found.owned.length) return null
127
+ const inside = found.owned.map((index) => found.lines[index]).join('\n')
128
+ const url = /^\s*url\s*=\s*"((?:[^"\\]|\\.)*)"/m.exec(inside)?.[1]
129
+ const key = /\bAuthorization\s*=\s*"Bearer ((?:[^"\\]|\\.)*)"/.exec(inside)?.[1]
130
+ // rawUrl 是原样写着的地址,只用来显示
131
+ return { url: unquoted(url).replace(/\/v1\/mcp$/, ''), key: unquoted(key), rawUrl: unquoted(url) }
132
+ }
133
+
134
+ // 新的全文:去掉 kioku 的 MCP 服务原来的那些行,把 block 加在最后(为 null 时只去掉;keep 为真时这一段原样留在原处),
135
+ // memoriesOff 为真时把 Memories 关掉。别的行原样不动,只收拾去掉的地方两边多出来的空行
136
+ function rewrite(found, block, { memoriesOff, keep = false }) {
137
+ const owned = new Set(keep ? [] : found.owned)
138
+ const lines = []
139
+ found.lines.forEach((line, index) => {
140
+ if (owned.has(index)) return
141
+ // 去掉一段之后,它前后的空行并成一行
142
+ if (line === '' && owned.has(index - 1) && (lines.at(-1) ?? '') === '') return
143
+ if (memoriesOff && found.memories?.value && index === found.memories.index) {
144
+ const [, head, , tail] = found.memories.parts
145
+ lines.push(`${head}false${tail}`)
146
+ } else lines.push(line)
147
+ })
148
+ if (!owned.size && !block) return lines.join(found.eol)
149
+ // 文件以一个换行结尾,新的一段前面空一行
150
+ while (lines.length && lines.at(-1) === '') lines.pop()
151
+ if (block) lines.push(...(lines.length ? [''] : []), ...block)
152
+ return lines.length ? `${lines.join(found.eol)}${found.eol}` : ''
153
+ }
154
+
155
+ // 现在的 config.toml 里有没有写着访问密钥:有的话不留备份,免得撤销、换访问密钥之后旧的还留在备份里
156
+ function holdsKey(found) {
157
+ return Boolean(blockValues(found)?.key)
158
+ }
159
+
160
+ // 记下的用户输入(钩子在每轮提交时写的):撤销时一起删掉
161
+ async function removePendingTurns(env) {
162
+ const dirs = [join(profileDir(env), 'codex-state')]
163
+ const data = join(codexHome(env), 'plugins', 'data')
164
+ for (const name of await readdir(data).catch(() => [])) {
165
+ if (name.startsWith('kioku-')) dirs.push(join(data, name, 'turns'))
166
+ }
167
+ for (const dir of dirs) await rm(dir, { recursive: true, force: true }).catch(() => {})
168
+ }
169
+
170
+ // 地址只打印协议、主机与路径;解析不了的压成一行再打印
171
+ function shown(url) {
172
+ try {
173
+ return shownUrl(url)
174
+ } catch {
175
+ return plainText(url)
176
+ }
177
+ }
178
+
179
+ const NEXT_STEPS = `接下来在 Codex 这一边:
180
+ 1. codex plugin marketplace add ${MARKETPLACE}
181
+ 2. codex plugin add kioku@kioku
182
+ 3. 打开 codex,在 /hooks 里信任 kioku 的三个钩子(没信任过的钩子不会运行)
183
+ `
184
+
185
+ async function undo({ dryRun }, { env, out }) {
186
+ const file = join(codexHome(env), 'config.toml')
187
+ const text = await readText(file)
188
+ const found = scanConfig(text)
189
+ const profile = profileFile('codex', env)
190
+ if (!found.owned.length) out.write(`${file} 里没有 Kioku 的 MCP 服务,不用改\n`)
191
+ else {
192
+ out.write(`${file}\n ${SERVER}:去掉\n`)
193
+ if (!dryRun) {
194
+ // 现在的文件里写着访问密钥,不留备份
195
+ await safeWrite(file, rewrite(found, null, { memoriesOff: false }), text, { backup: false })
196
+ }
197
+ }
198
+ if (found.unsupported) {
199
+ out.write(`${file} 里还有用别的写法定义的 kioku 服务,没有改动它,要手动去掉\n`)
200
+ }
201
+ if (dryRun) out.write(`${profile}:删掉\n没有写入(--dry-run)\n`)
202
+ else {
203
+ if (await removeProfile('codex', env)) out.write(`已删掉 ${profile}\n`)
204
+ await removePendingTurns(env)
205
+ }
206
+ out.write('Codex 自带的 Memories 没有重新打开:要用的话运行 codex features enable memories\n')
207
+ out.write('插件要另外卸载:codex plugin remove kioku@kioku\n')
208
+ return 0
209
+ }
210
+
211
+ export async function setupCodex(options, io) {
212
+ const { env, out } = io
213
+ if (options.undo) return undo(options, io)
214
+ const file = join(codexHome(env), 'config.toml')
215
+ const text = await readText(file)
216
+ const found = scanConfig(text)
217
+
218
+ const refuseUnsupported = () => {
219
+ if (!found.unsupported) return
220
+ throw new KiokuFailure(
221
+ `${file} 里已经用行内表或带点的键定义了 kioku 这个 MCP 服务,没有改动它:删掉那个定义后重新运行`,
222
+ )
223
+ }
224
+ // 要走浏览器授权时先看这个:访问密钥签发了却写不进去的话,会留下一个没人拿着的
225
+ const { url, key, saved } = await resolveTarget({ id: 'codex', name: 'Codex' }, options, {
226
+ ...io,
227
+ beforeLogin: refuseUnsupported,
228
+ })
229
+ // 地址与访问密钥都定下来之后、写文件之前再看一次
230
+ refuseUnsupported()
231
+
232
+ const before = blockValues(found)
233
+ const sameBlock = Boolean(before && key && before.url === url && before.key === key)
234
+ const changes = []
235
+ if (!sameBlock) {
236
+ const was = !before ? '(未设置)' : before.rawUrl ? shown(before.rawUrl) : '(认不出的写法)'
237
+ // 地址没变时只是换访问密钥,不把同一个地址写两遍
238
+ if (before?.url === url) changes.push(` ${SERVER}:换访问密钥`)
239
+ else changes.push(` ${SERVER}:${was} → ${shown(url)}/v1/mcp`)
240
+ }
241
+ if (found.memories?.value) changes.push(' features.memories:true → false')
242
+ const profile = profileFile('codex', env)
243
+ const sameProfile = Boolean(saved && saved.url === url && saved.key === key)
244
+
245
+ if (!changes.length) out.write(`${file} 不用改\n`)
246
+ else out.write(`${file}\n${changes.join('\n')}\n`)
247
+ if (!sameProfile) out.write(`${profile}:写入服务地址与访问密钥(只给本人读写)\n`)
248
+ if (options.dryRun) {
249
+ out.write('没有写入(--dry-run)\n')
250
+ return 0
251
+ }
252
+ if (changes.length) {
253
+ const body = sameBlock
254
+ ? rewrite(found, null, { memoriesOff: true, keep: true })
255
+ : rewrite(found, blockOf({ url, key }), { memoriesOff: true })
256
+ const backedUp = await safeWrite(file, body, text, { backup: !holdsKey(found) })
257
+ if (backedUp) out.write(`原来的设置备份在 ${file}.kioku-backup\n`)
258
+ }
259
+ if (!sameProfile) await writeProfile('codex', { url, key }, env)
260
+ if (found.memoriesUnknown) {
261
+ out.write(
262
+ `! ${file} 里 features 的写法认不出来,没有核对 Memories:运行 codex features disable memories 关掉它\n`,
263
+ )
264
+ }
265
+ out.write(`Codex 已配好,新开会话生效。\n${found.plugin || io.hints === false ? '' : NEXT_STEPS}`)
266
+ return 0
267
+ }
268
+
269
+ // kioku login 申请之前先看:config.toml 写不写得进去
270
+ export async function preflightCodex({ env }) {
271
+ const file = join(codexHome(env), 'config.toml')
272
+ if (scanConfig(await readText(file)).unsupported) {
273
+ throw new KiokuFailure(
274
+ `${file} 里已经用行内表或带点的键定义了 kioku 这个 MCP 服务:删掉那个定义后重新运行`,
275
+ )
276
+ }
277
+ }
278
+
279
+ export async function inspectCodex({ env }, { ok, warn, bad, note }) {
280
+ const file = join(codexHome(env), 'config.toml')
281
+ const found = scanConfig(await readText(file))
282
+ const profile = await readProfile('codex', env).catch(() => null)
283
+ if (!profile) {
284
+ warn('没有 kioku setup codex 写下的地址与访问密钥,钩子不会生效:运行 kioku setup codex')
285
+ }
286
+
287
+ const block = blockValues(found)
288
+ if (found.unsupported) {
289
+ warn(`${file} 里的 kioku 服务用了行内表或带点的键,没有核对它:改成 kioku setup codex 的写法`)
290
+ } else if (!block) {
291
+ warn(`${file} 里没有 Kioku 的 MCP 服务,读写记忆的工具用不了:运行 kioku setup codex`)
292
+ } else if (profile && (block.url !== profile.url || block.key !== profile.key)) {
293
+ bad(`${file} 里 Kioku 的 MCP 服务和钩子用的地址或访问密钥对不上:重新运行 kioku setup codex`)
294
+ } else ok('Codex 里配了 Kioku 的 MCP 服务')
295
+
296
+ if (found.plugin) ok('Codex 的 kioku 插件已启用')
297
+ else {
298
+ warn(
299
+ `Codex 的 kioku 插件没有启用:codex plugin marketplace add ${MARKETPLACE},再 codex plugin add kioku@kioku`,
300
+ )
301
+ }
302
+ note('钩子要在 Codex 的 /hooks 里信任过才会运行,这里查不到')
303
+
304
+ if (found.memoriesUnknown && !found.memories) {
305
+ warn(`${file} 里 features 的写法认不出来,没有核对 Memories:用 codex features list 看它开没开`)
306
+ } else if (found.memories?.value) {
307
+ warn('Codex 自带的 Memories 开着,会和 Kioku 各记一份:运行 kioku setup codex 关掉它')
308
+ } else ok('Codex 自带的 Memories 没有启用')
309
+ }
310
+
311
+ // 给向导的面板:插件启用没有、自带的 Memories 关了没有(null 是认不出)
312
+ export async function statusCodex({ env }) {
313
+ const found = scanConfig(await readText(join(codexHome(env), 'config.toml')))
314
+ const memory = found.memories?.value
315
+ ? 'on'
316
+ : found.memoriesUnknown && !found.memories
317
+ ? null
318
+ : 'off'
319
+ return { plugin: found.plugin, memory }
320
+ }