@kioku-memory/cli 0.0.0 → 0.2.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/NOTICE CHANGED
@@ -2,3 +2,6 @@ kioku-plugins
2
2
  Copyright 2026 lonelyman0108
3
3
 
4
4
  This product is licensed under the Apache License, Version 2.0 (see LICENSE).
5
+
6
+ packages/core/lib/command.mjs 里给 cmd.exe 转义参数的规则改写自 cross-spawn
7
+ (https://github.com/moxystudio/node-cross-spawn),MIT License,Copyright (c) 2018 Made With MOXY Lda。
package/README.md CHANGED
@@ -8,17 +8,64 @@ npx @kioku-memory/cli doctor
8
8
  npm install -g @kioku-memory/cli
9
9
  ```
10
10
 
11
- Claude Code 的 kioku 插件自带同一个命令,启用插件后在它的 Bash 工具里直接用 `kioku`,不用另装。
11
+ Claude Code 的 kioku 插件自带同一个命令,启用插件后在它的 Bash 工具里直接用 `kioku`,不用另装(插件里的那份没有向导)。
12
+
13
+ ## 向导
14
+
15
+ 在终端里不带参数运行 `kioku`,要 Node 20.12 或更新的版本。先扫描一遍现状:
16
+
17
+ - 服务器:地址(取各平台已有的配置或 `KIOKU_SERVER_URL`,都没有就问)、连不连得上、版本、初始化了没有。
18
+ - 每个平台一行:本机装没装(命令或配置目录在不在)、接到哪个应用和空间、访问密钥是否有效、插件装没装、自带的长期记忆停没停、本地有几条记忆。查不了的写「无法判断」。
19
+
20
+ 下面按缺什么列出动作,例如「接入 Codex、pi(2 个未接入)」「重新授权 Hermes(访问密钥已失效)」「接入 Claude Code」「迁移 Claude Code 的本地记忆(12 条)」「停用某个平台」「本机起一个 Kioku」「检查(doctor)」。每个动作先列计划、确认后才做,做完回到面板。
21
+
22
+ - **接入几个平台只确认一次**:一次申请勾选的几个平台(最多 8 个,多了分批,每批确认一次),确认页上为每个平台选应用与权限;拿到的访问密钥照 `kioku setup` 写下。确认页上没勾的平台跳过;确认之后、取走之前不再符合签发规则的(例如确认人已停用、应用被删)列出原因。服务端版本较旧、不认这种申请时,逐个平台申请,每个确认一次。签发了却没能写下的,提示去管理界面吊销。
23
+ - **迁移本地记忆**:面板上只数本地有几条;选了迁移才和 Kioku 逐条比对、列出计划,比出来的未迁移条数在这次向导里显示,写入之后重新算。比对失败的写「未迁移 无法判断」。
24
+ - **插件不替你装**:做完列出每个平台要自己运行的安装命令与之后要做的事,装好之后再运行 `kioku`,面板上就是「已安装」。
25
+ - **Claude Code**:访问密钥只认它的 `/plugin` 里填的,浏览器授权不给它发。「接入 Claude Code」停用自动记忆,再列出 `/plugin` 的安装命令与要填的服务地址;迁移本地记忆时问一次访问密钥。项目的 `.claude/settings.json` 又启用了自动记忆时,面板写明是哪份文件,不再提供停用(要在那里改)。
26
+ - **本机起一个 Kioku**:没有服务器时可选。取 Kioku 最新的正式版,在一个目录(默认 `~/kioku`)里下载这个版本的 `compose.yaml` 与 `.env.example`,生成 `.env`(数据库密码、主密钥、初始化码随机生成,镜像固定在这个版本,只给本人读写,端口只开在本机,已有的 `.env` 不覆盖),`docker compose up -d`,等服务就绪后显示初始化码并打开管理界面,建好管理员就接着接入平台。取不到正式版时用 main 上的文件与 `edge` 镜像,并明说。主密钥在 `.env` 里,另外保存一份。目录里已经起过(上次中断、重跑)的接着启动或等它就绪;端口 18920 被别的程序占着时只说明,不动它。
12
27
 
13
28
  ## 子命令
14
29
 
15
30
  | 子命令 | 作用 |
16
31
  |---|---|
17
- | `kioku setup <平台>` | 停用平台自带的长期记忆,由 Kioku 接管 |
32
+ | `kioku install --platforms <平台,…>` | 几个平台一起接入,访问密钥从环境变量读(给脚本用) |
33
+ | `kioku setup <平台>` | 把平台交给 Kioku 接管:停用平台自带的长期记忆;Codex、pi、Hermes、OpenClaw、DeepSeek Harness 再写下服务地址与访问密钥,Codex 还配好 MCP 服务 |
34
+ | `kioku login <平台>` | 用浏览器授权签发访问密钥并配好这个平台,不用手动复制 |
18
35
  | `kioku doctor [平台]` | 检查地址、访问密钥与平台的配置 |
36
+ | `kioku import --from <来源>` | 把平台自带的本地长期记忆迁进 Kioku |
19
37
  | `kioku run -e 变量=<标识>#<字段> -- <命令>` | 向 Kioku 取凭据的值,放进环境变量交给命令 |
20
38
 
21
- 每个子命令的完整说明:`kioku <子命令> --help`。现在认得的平台:`claude-code`。
39
+ 每个子命令的完整说明:`kioku <子命令> --help`。现在认得的平台:`claude-code`、`codex`、`pi`、`hermes`、`openclaw`、`dsh`。
40
+
41
+ ## login
42
+
43
+ ```bash
44
+ kioku login codex --server-url https://kioku.example.com
45
+ ```
46
+
47
+ 终端显示一个确认码并打开 Kioku 管理界面的确认页(`--no-browser` 时只显示地址)。登录后在页面上输入确认码,选空间、应用与权限范围,点确认;命令行取到访问密钥后接着做 `kioku setup` 的事:核对、写下配置。访问密钥全程不显示。认得 `codex`、`pi`、`hermes`、`openclaw`、`dsh`;Claude Code 的访问密钥在它的 `/plugin` 里填。
48
+
49
+ - 确认码不在打开的地址里,要照着终端输入:只在自己刚运行了这条命令时确认。别人发来一个确认码让你去确认的,不要确认,那样对方的机器会拿到能读写你的记忆的访问密钥。
50
+ - 申请 10 分钟内有效。被拒绝、过期,或者确认之后确认人的角色变了,都拿不到访问密钥,重新运行即可。
51
+ - 不用在本机开端口,远程登录的机器上也能用:在任何一台登录了管理界面的浏览器里确认都行。
52
+ - 要 Kioku 服务端支持浏览器授权;旧的服务端会提示改用 `kioku setup` 手动填访问密钥。
53
+
54
+ `kioku setup codex`、`kioku setup pi` 第一次配置时,在终端里提示输入访问密钥的地方直接回车,走的是同一个流程。已经配过的再运行 `setup`,直接回车是沿用上次的访问密钥;要换一个就运行 `kioku login`。
55
+
56
+ - 确认之后如果这台机器没能把访问密钥写下(配置文件写不进去、中途断网),命令会提示去管理界面的应用页吊销刚签发的那个,再重新运行:访问密钥只在签发时给一次。
57
+
58
+ ## install
59
+
60
+ ```bash
61
+ export KIOKU_API_KEY_CODEX=… KIOKU_API_KEY_PI=…
62
+ kioku install --platforms codex,pi --server-url https://kioku.example.com -y
63
+ ```
64
+
65
+ 每个平台的访问密钥放在 `KIOKU_API_KEY_<平台>` 里(平台名大写、连字符换成下划线:`KIOKU_API_KEY_CLAUDE_CODE`、`KIOKU_API_KEY_CODEX`、`KIOKU_API_KEY_PI`、`KIOKU_API_KEY_HERMES`、`KIOKU_API_KEY_OPENCLAW`、`KIOKU_API_KEY_DSH`),没给的平台跳过并在结果里列出。各平台照 `kioku setup` 核对、写下配置、停用自带的长期记忆;Claude Code 只核对访问密钥、停用自动记忆,地址与访问密钥要在它的 `/plugin` 里填。
66
+
67
+ - 在终端里运行、没带 `-y` 时先列计划再确认;`--dry-run` 只列计划。
68
+ - 最后列出要自己运行的插件安装命令。有平台失败时退出码为 1。
22
69
 
23
70
  ## setup
24
71
 
@@ -35,6 +82,46 @@ kioku setup claude-code --undo # 改回去
35
82
 
36
83
  不停用的话,平台自带的记忆和 Kioku 会各记一份,两边的内容迟早对不上。
37
84
 
85
+ ### Codex
86
+
87
+ ```bash
88
+ kioku setup codex --server-url https://kioku.example.com
89
+ ```
90
+
91
+ 提示输入访问密钥(不回显;也可以放在 `KIOKU_API_KEY` 里或从标准输入给),核对后写下 `~/.config/kioku/codex.json`,在 `~/.codex/config.toml` 里加上 Kioku 的 MCP 服务并关掉 Memories,再列出在 Codex 这一边要做的三步。改了什么、怎么撤销见 [Codex 插件的说明](https://github.com/lonelyman0108/kioku-plugins/tree/main/plugins/codex#setup-改了什么)。
92
+
93
+ ### pi
94
+
95
+ ```bash
96
+ kioku setup pi --server-url https://kioku.example.com
97
+ ```
98
+
99
+ 核对后写下 `~/.config/kioku/pi.json`,不改 pi 的设置(pi 没有自带的长期记忆,MCP 服务由扩展注册)。扩展用 `pi install git:github.com/lonelyman0108/kioku-plugins` 装。
100
+
101
+ ### Hermes
102
+
103
+ ```bash
104
+ kioku setup hermes --server-url https://kioku.example.com
105
+ ```
106
+
107
+ 核对后把地址与访问密钥写进 `~/.hermes/.env`,再经 `hermes config set` 选 Kioku 做记忆 provider、关掉内置的 `MEMORY.md` 与 `USER.md`。provider 用 `hermes plugins install lonelyman0108/kioku-plugins/plugins/hermes --enable` 装。细节见 [Hermes provider 的说明](https://github.com/lonelyman0108/kioku-plugins/tree/main/plugins/hermes#setup-改了什么)。
108
+
109
+ ### OpenClaw
110
+
111
+ ```bash
112
+ kioku setup openclaw --server-url https://kioku.example.com
113
+ ```
114
+
115
+ 核对后写下 `~/.config/kioku/openclaw.json`,再经 `openclaw config set` 允许插件读对话(`plugins.entries.kioku.hooks.allowConversationAccess`);记忆槽位在装插件时由 OpenClaw 选上,被换走了才由 `setup` 选回来。插件用 `openclaw plugins install npm:@kioku-memory/openclaw` 装,装完重启网关。细节见 [OpenClaw 插件的说明](https://github.com/lonelyman0108/kioku-plugins/tree/main/plugins/openclaw#setup-改了什么)。
116
+
117
+ ### DeepSeek Harness
118
+
119
+ ```bash
120
+ kioku setup dsh --server-url https://kioku.example.com
121
+ ```
122
+
123
+ 核对后写下 `~/.config/kioku/dsh.json`,不改 dsh 的设置(它没有自带的长期记忆)。插件按 profile 装:`dsh plugin --profile <profile> add github:lonelyman0108/kioku-plugins`,装完重启 dsh。
124
+
38
125
  ## doctor
39
126
 
40
127
  ```bash
@@ -43,9 +130,47 @@ kioku doctor claude-code
43
130
 
44
131
  每项一行:`✓` 正常,`!` 要留意,`✗` 有问题(这时退出码为 1)。查的是:地址连不连得上、访问密钥是否有效、它属于哪个应用、能读写哪些归属、最高敏感级与凭据能力,以及平台这一边插件是否启用、自带的长期记忆是否已停用。不写平台时按当前所在的会话认。
45
132
 
133
+ ## import
134
+
135
+ ```bash
136
+ kioku import --from claude-code --dry-run # 只看计划
137
+ kioku import --from claude-code # 列出计划,确认后写入
138
+ ```
139
+
140
+ 先读本地的记忆文件,列出每条会放到哪个坐标、Kioku 里有没有,确认之后才写。本地的文件不删、不改。
141
+
142
+ | 来源 | 读什么 | 放到哪 |
143
+ |---|---|---|
144
+ | `claude-code` | `~/.claude/projects/*/memory/*.md`(`MEMORY.md` 是索引,不读) | 按文件头里的类型:`user` → `user://about/<项目>/<名字>`;`project` → `user://projects/<项目>/<名字>`;`reference` → `user://reference/<项目>/<名字>`;`feedback` → `app://<应用>/feedback/<项目>/<名字>` |
145
+ | `hermes` | `~/.hermes/memories/` 的 `MEMORY.md`、`USER.md` | `MEMORY.md` → `app://<应用>/hermes/notes/…`;`USER.md` → `user://about/hermes/…` |
146
+ | `openclaw` | `~/.openclaw/workspace/` 的 `MEMORY.md`、`USER.md` 与 `memory/` 里按日期的笔记(`<日期>.md`、`<日期>-<名字>.md`) | `MEMORY.md` → `app://<应用>/openclaw/notes/…`;`USER.md` → `user://about/openclaw/…`;按日期的笔记 → `app://<应用>/openclaw/journal/<文件名>`,一个文件一条 |
147
+
148
+ - `<应用>` 是访问密钥所属的应用的标识。偏「这个 agent 该怎么干活」的放在应用下,别的 agent 用不上;关于用户本人和项目的放在本人下,各个 agent 都读得到。
149
+ - `<项目>` 取自 Claude Code 的项目目录名,去掉主目录与 `Documents`、`code` 这类常见的上级目录。分不清的两个项目(例如 `~/code/dev-proxy` 与 `~/code/proxy`)会得到同一个名字,同名的记忆会在计划里标出来,不会悄悄顶掉。
150
+ - Hermes、OpenClaw 的一个文件拆成几条:有只写着 `§` 的分隔行就按它拆,否则按二级标题拆,都没有就是一整条。有标题的用标题做标识;没有标题的用内容的摘要,所以文件里插一条、删一条不影响别的条,但改了某一段的内容会新建一条、旧的留着。Hermes 的位置与分隔符已经对着它的源码核对过(0.19.0),OpenClaw 的位置与文件名对着真实的安装核对过(2026.6.35)。OpenClaw 的 `USER.md` 是它生成的模板,没填过的话计划里会列出模板本身,不想要就先别迁。
151
+ - 标题与触发场景取文件头里的说明。写进去的记忆优先级是默认的,不进启动加载;要进的在管理界面里改。
152
+ - **重复运行不重复写**:坐标由来源决定,已经有、内容一样的跳过;已经有、内容不一样的默认也跳过(可能在 Kioku 里改过),`--overwrite` 才覆盖。
153
+ - **疑似明文凭据的不写**:列出是哪个文件、正文第几行、哪一类,不带值。先把值存成凭据、正文里写占位符,或者从文件里去掉,再运行一次。
154
+ - 不迁的会列出原因:正文超过 2 万字、没有内容、名字规整之后和别的一条撞了、文件头没有结尾。
155
+ - 只读普通的文本文件:符号链接不跟(它可以指到记忆目录之外的文件),太大的、不是文本的不读。
156
+ - 写到一半连不上时停下来,说明写了多少、还剩多少;重新运行会接着写。
157
+ - 不在终端里运行时要带 `--yes` 才写。`--path` 指明不在默认位置的目录。
158
+ - 地址与访问密钥读环境变量(Claude Code 的会话里已经配好);`--platform codex`、`--platform pi`、`--platform hermes`、`--platform openclaw` 或 `--platform dsh` 改用 `kioku setup` 给那个平台写下的。记忆迁进这个访问密钥所属的应用。
159
+ - 指令文件(`AGENTS.md`、`CLAUDE.md`)不是记忆,不迁。Codex 自带的 Memories 存在它自己的数据库里、格式没有公开,迁不了。
160
+
161
+ 迁完之后用 `kioku setup <平台>` 停用平台自带的记忆,免得两边接着各记一份。
162
+
163
+ ## 各系统
164
+
165
+ macOS 与 Linux 上各平台都用真实的模型实测过。Windows 上跑过单元用例,也在 CI 的 Windows 机器上装真实的平台走过一遍(pi、Codex、OpenClaw、Hermes、DeepSeek Harness;模型是假的,核对的是装插件、注入、上报与工具登记),交互界面没有看过:
166
+
167
+ - 配置文件在 `%USERPROFILE%\.config\kioku\`(和别的系统一样的相对位置,可以用 `KIOKU_CONFIG_DIR` 改)。Windows 没有 600 这种权限位,文件靠用户目录自己的访问控制保护。
168
+ - npm 装的命令是 `.cmd`:`kioku setup openclaw`、`kioku run -- npm …` 会经 `cmd.exe` 起它们,参数里的 `&`、`|`、`%` 这类字符照原样交给命令。
169
+ - `kioku run` 转发信号(Ctrl-C、终止)的行为只在 macOS、Linux 上核对过。
170
+
46
171
  ## 地址与访问密钥
47
172
 
48
- `doctor` 与 `run` 从环境变量读:
173
+ `kioku doctor codex`、`kioku doctor pi`、`kioku doctor hermes`、`kioku doctor openclaw`、`kioku doctor dsh` 读 `kioku setup` 写下的配置。别的情况下 `doctor` 与 `run` 从环境变量读:
49
174
 
50
175
  - `KIOKU_SERVER_URL`:例如 `https://kioku.example.com`,不带 `/v1`
51
176
  - `KIOKU_API_KEY`:在 Kioku 管理界面的「应用」页签发的访问密钥;或者用 `KIOKU_API_KEY_FILE` 指向只含访问密钥的文件
package/bin/kioku CHANGED
@@ -10,6 +10,17 @@ const load = (name) =>
10
10
  },
11
11
  )
12
12
 
13
+ // 输出被读的一方提前关掉(kioku doctor | head):之后的输出写不出去就算了,不抛一段堆栈;
14
+ // 手上的事照常做完、按它的结果退出(中途停下的话,写了一半的导入、配置会被当成成功)。别的写入错误照旧抛。
15
+ // run 不在此列:它转发命令的输出,自己处理这种情况
16
+ if (process.argv[2] !== 'run') {
17
+ for (const stream of [process.stdout, process.stderr]) {
18
+ stream.on('error', (err) => {
19
+ if (!err || err.code !== 'EPIPE') throw err
20
+ })
21
+ }
22
+ }
23
+
13
24
  load('kioku.mjs')
14
25
  .then((cli) => cli.main(process.argv.slice(2)))
15
26
  .then((code) => {
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/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
+ 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
+ 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
+ }