@kioku-memory/cli 0.6.1 → 0.6.2-edge.20261127111942.gcfb34f8

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
@@ -8,3 +8,7 @@ packages/core/lib/command.mjs 里给 cmd.exe 转义参数的规则改写自 cros
8
8
 
9
9
  plugins/opencode/index.js 里的对话事件映射与系统提示标记做法参考自 Lore
10
10
  (opencode-plugin),MIT License,Copyright (c) Lore contributors。
11
+
12
+ plugins/zcode 与 packages/cli/src/zcode.ts 里的 ZCode 插件目录布局(.zcode-plugin/plugin.json、
13
+ marketplace.json、process 钩子格式)与插件市场注册命令参考自 Lore(https://github.com/FFatTiger/lore),
14
+ MIT License,Copyright (c) 2025 Salem / Lore contributors。
package/README.md CHANGED
@@ -23,7 +23,7 @@ Claude Code、Codex 等插件目录内部保留精简的 `packages/core` 运行
23
23
  底栏按当前选中客户端状态提供单键快捷操作(`Enter` 接入或重授权、`a` 批量接入、`p` 安装/更新插件、`d` 诊断、`i` 迁移本地记忆、`x` 清理冲突工具、`u` 断开并恢复自带记忆、`y` 复制安装命令、`?` 查看全部快捷键)。执行修改类动作前先弹出确认框,浏览器授权确认框与进度等待同样在工作台弹出层内完成:
24
24
 
25
25
  - **多平台联合授权**:一次申请勾选的几个平台(最多 8 个),终端弹出宽松确认码框并自动尝试复制确认码,附带 `[o]` 打开浏览器 / `[c]` 复制链接 / `[Esc]` 取消快捷键与 10 分钟实时倒计时。浏览器确认页只输入一次确认码即可完成全部选定平台的配置写入、自带记忆停用,并自动尝试安装对应插件与执行 `whoami` + MCP `tools/list` 连通性握手测试。
26
- - **插件自动安装与托管更新**:支持调用 Claude Code、Codex、Gemini CLI、pi、Hermes、OpenClaw 的官方安装/更新命令,或同步内置 Antigravity / Gemini 扩展(Antigravity 目录带 `.kioku-managed.json` 托管标记,更新或 `kioku disconnect` 清理时绝不误删用户自己放置的目录);未检测到客户端 CLI 时自动降级为可复制的手动命令。
26
+ - **插件自动安装与托管更新**:支持调用 Claude Code、Codex、Gemini CLI、ZCode、pi、Hermes、OpenClaw 的官方安装/更新命令,或同步内置 Antigravity / Gemini / ZCode 插件(托管目录带 `.kioku-managed.json` 标记,更新或 `kioku disconnect` 清理时绝不误删用户自己放置的目录);未检测到客户端 CLI 时自动降级为可复制的手动命令。
27
27
  - **Claude Code 统一鉴权**:`kioku connect claude-code` 与 `kioku login claude-code` 直接走浏览器授权写入 `~/.config/kioku/claude-code.json` 并配好 `autoMemoryEnabled: false`;在 `/plugin` 里填入的配置优先,`/plugin` 留空时插件钩子与 `mcp-stdio.mjs` 自动回退读取 `~/.config/kioku/claude-code.json`。
28
28
  - **迁移本地记忆**:控制台仅统计本地条数;选定迁移后与服务端逐条比对并列出计划,支持 `--select` 勾选子集写入。
29
29
  - **在本机启动 Kioku**:没有服务器时可在 `~/kioku` 生成 `compose.yaml` 与仅本人可读写的随机密钥 `.env`,`docker compose up -d` 等健康检查通过后展示初始化码并在浏览器打开管理界面。
@@ -54,7 +54,7 @@ Claude Code、Codex 等插件目录内部保留精简的 `packages/core` 运行
54
54
  | `kioku install --platforms <平台,…>` | 多个平台批量接入,访问密钥从环境变量读(给脚本用) |
55
55
  | `kioku run -e 变量=<标识>[#<字段>] -- <命令>` | 向 Kioku 取凭据的值,放进环境变量交给命令 |
56
56
 
57
- 每个子命令的完整说明:`kioku <子命令> --help`,查看版本号:`kioku --version`(或 `-v`)。支持的平台:`claude-code`、`codex`、`gemini`、`agy`、`opencode`、`pi`、`hermes`、`openclaw`、`dsh`。
57
+ 每个子命令的完整说明:`kioku <子命令> --help`,查看版本号:`kioku --version`(或 `-v`)。支持的平台:`claude-code`、`codex`、`gemini`、`agy`、`opencode`、`pi`、`hermes`、`openclaw`、`dsh`、`zcode`。
58
58
 
59
59
  ## 从旧版迁移
60
60
 
@@ -70,7 +70,7 @@ Claude Code、Codex 等插件目录内部保留精简的 `packages/core` 运行
70
70
  kioku login codex --server-url https://kioku.example.com
71
71
  ```
72
72
 
73
- 终端显示确认码框并打开 Kioku 管理界面的确认页(`--no-browser` 时只显示地址)。登录后在页面上输入确认码,选好场域、环境与权限范围,点确认;命令行取到访问密钥后接着做 `kioku setup` 的事:核对、写下配置。访问密钥全程不显示。支持全部客户端:`claude-code`、`codex`、`gemini`、`agy`、`opencode`、`pi`、`hermes`、`openclaw`、`dsh`。
73
+ 终端显示确认码框并打开 Kioku 管理界面的确认页(`--no-browser` 时只显示地址)。登录后在页面上输入确认码,选好场域、环境与权限范围,点确认;命令行取到访问密钥后接着做 `kioku setup` 的事:核对、写下配置。访问密钥全程不显示。支持全部客户端:`claude-code`、`codex`、`gemini`、`agy`、`opencode`、`pi`、`hermes`、`openclaw`、`dsh`、`zcode`。
74
74
 
75
75
  - 确认码不在打开的地址里,要照着终端输入:只在自己刚运行了这条命令时确认。别人发来确认码请求代为确认时切勿通过,那样对方的机器会拿到能读写本人记忆的访问密钥。
76
76
  - 申请 10 分钟内有效。被拒绝或过期时,重新运行即可。
@@ -88,7 +88,7 @@ export KIOKU_API_KEY_CODEX=… KIOKU_API_KEY_PI=…
88
88
  kioku install --platforms codex,pi --server-url https://kioku.example.com -y
89
89
  ```
90
90
 
91
- 每个平台的访问密钥放在 `KIOKU_API_KEY_<平台>` 里(平台名大写、连字符换成下划线:`KIOKU_API_KEY_CLAUDE_CODE`、`KIOKU_API_KEY_CODEX`、`KIOKU_API_KEY_GEMINI`、`KIOKU_API_KEY_AGY`、`KIOKU_API_KEY_OPENCODE`、`KIOKU_API_KEY_PI`、`KIOKU_API_KEY_HERMES`、`KIOKU_API_KEY_OPENCLAW`、`KIOKU_API_KEY_DSH`),没给的平台跳过并在结果里列出。各平台照 `kioku setup` 核对、写下本机配置并停用自带长期记忆。
91
+ 每个平台的访问密钥放在 `KIOKU_API_KEY_<平台>` 里(平台名大写、连字符换成下划线:`KIOKU_API_KEY_CLAUDE_CODE`、`KIOKU_API_KEY_CODEX`、`KIOKU_API_KEY_GEMINI`、`KIOKU_API_KEY_AGY`、`KIOKU_API_KEY_OPENCODE`、`KIOKU_API_KEY_PI`、`KIOKU_API_KEY_HERMES`、`KIOKU_API_KEY_OPENCLAW`、`KIOKU_API_KEY_DSH`、`KIOKU_API_KEY_ZCODE`),没给的平台跳过并在结果里列出。各平台照 `kioku setup` 核对、写下本机配置并停用自带长期记忆。
92
92
 
93
93
  - 在终端里运行、没带 `-y` 时先列计划再确认;`--dry-run` 只列计划。
94
94
  - 最后列出要自己运行的插件安装命令。有平台失败时退出码为 1。
@@ -172,6 +172,14 @@ kioku setup opencode --server-url https://kioku.example.com
172
172
 
173
173
  核对后写下 `~/.config/kioku/opencode.json`,并在 `~/.config/opencode/opencode.json` 的 `plugin` 列表里加上 `@kioku-memory/plugin-opencode`(原文件备份成 `opencode.json.kioku-backup`;OpenCode 没有自带的长期记忆,MCP 由插件在 `config` 钩子里注册)。
174
174
 
175
+ ### ZCode
176
+
177
+ ```bash
178
+ kioku setup zcode --server-url https://kioku.example.com
179
+ ```
180
+
181
+ 核对后写下 `~/.config/kioku/zcode.json`(插件自带生命周期钩子与 stdio MCP 桥接,均从该文件读取地址与访问密钥)。使用 `kioku connect zcode` 可自动把内置插件目录注册到 ZCode 插件市场并启用 `kioku@kioku`,也可手动执行 `zcode plugins marketplace add`、`zcode plugins install kioku@kioku`、`zcode plugins enable kioku@kioku`。
182
+
175
183
  ## 日常记忆读写(search / get / ls / add / edit / delete / boot)
176
184
 
177
185
  这些日常记忆命令共用零配置身份解析链:优先读 `--platform <平台>`,其次读 `KIOKU_SERVER_URL` + `KIOKU_API_KEY`(或 `KIOKU_API_KEY_FILE`),再读 `~/.config/kioku/cli.json` 记住的默认身份;本机若仅配置了一个客户端则直接选用,存在多个客户端时在交互式终端交互选择并记住默认项(非终端环境下提示传入 `--platform`)。
@@ -247,7 +255,7 @@ kioku import --from claude-code -y # 免确认直接写入
247
255
  - 只读普通的文本文件:符号链接不跟(它可以指到记忆目录之外的文件),太大的、不是文本的不读。
248
256
  - 写到一半连不上时停下来,说明写了多少、还剩多少;重新运行会接着写。
249
257
  - 不在终端里运行时要带 `--yes` 才写。`--path` 指明不在默认位置的目录。
250
- - 地址与访问密钥读环境变量(Claude Code 的会话里已经配好);`--platform codex`、`--platform gemini`、`--platform agy`、`--platform opencode`、`--platform pi`、`--platform hermes`、`--platform openclaw` 或 `--platform dsh` 改用 `kioku setup` 给那个平台写下的。
258
+ - 地址与访问密钥读环境变量(Claude Code 的会话里已经配好);`--platform codex`、`--platform gemini`、`--platform agy`、`--platform opencode`、`--platform pi`、`--platform hermes`、`--platform openclaw`、`--platform dsh` 或 `--platform zcode` 改用 `kioku setup` 给那个平台写下的。
251
259
  - 指令文件(`AGENTS.md`、`CLAUDE.md`)不是记忆,不迁。Codex 自带的 Memories 存在它自己的数据库里、格式没有公开,迁不了。
252
260
 
253
261
  迁完之后用 `kioku setup <平台>` 停用平台自带的记忆,免得两边接着各记一份。
@@ -262,7 +270,7 @@ macOS 与 Linux 上各平台都用真实的模型实测过。Windows 上跑过
262
270
 
263
271
  ## 地址与访问密钥
264
272
 
265
- `kioku doctor claude-code`、`kioku doctor codex`、`kioku doctor gemini`、`kioku doctor agy`、`kioku doctor opencode`、`kioku doctor pi`、`kioku doctor hermes`、`kioku doctor openclaw`、`kioku doctor dsh` 读 `kioku setup` 写下的配置。别的情况下 `doctor` 与 `run` 从环境变量读:
273
+ `kioku doctor claude-code`、`kioku doctor codex`、`kioku doctor gemini`、`kioku doctor agy`、`kioku doctor opencode`、`kioku doctor pi`、`kioku doctor hermes`、`kioku doctor openclaw`、`kioku doctor dsh`、`kioku doctor zcode` 读 `kioku setup` 写下的配置。别的情况下 `doctor` 与 `run` 从环境变量读:
266
274
 
267
275
  - `KIOKU_SERVER_URL`:例如 `https://kioku.example.com`,不带 `/v1`
268
276
  - `KIOKU_API_KEY`:在 Kioku 管理界面的「设置 → 连接与终端」签发的访问密钥;或者用 `KIOKU_API_KEY_FILE` 指向只含访问密钥的文件
@@ -0,0 +1,11 @@
1
+ {
2
+ "mcpServers": {
3
+ "kioku": {
4
+ "type": "stdio",
5
+ "command": "node",
6
+ "args": ["${ZCODE_PLUGIN_ROOT}/hooks/mcp-stdio.mjs"],
7
+ "cwd": "${ZCODE_PROJECT_DIR}",
8
+ "timeoutMs": 30000
9
+ }
10
+ }
11
+ }
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "kioku",
3
+ "version": "0.6.1",
4
+ "description": "Kioku 长期记忆:会话开始注入启动加载,每轮注入召回候选,每轮回复后写会话摘要,并通过内置 MCP 桥接提供记忆工具",
5
+ "author": {
6
+ "name": "Kioku"
7
+ },
8
+ "homepage": "https://github.com/lonelyman0108/kioku",
9
+ "repository": "https://github.com/lonelyman0108/kioku-plugins",
10
+ "license": "Apache-2.0",
11
+ "keywords": ["memory", "zcode", "hooks", "mcp"]
12
+ }
@@ -0,0 +1,48 @@
1
+ # Kioku 的 ZCode 插件
2
+
3
+ 把 Kioku 接到 ZCode:会话开始时注入启动加载,每轮输入时注入召回候选,每轮结束后把该轮对话提交给 Kioku 提炼会话摘要,并通过内置 stdio MCP 桥接提供 Kioku 记忆工具。
4
+
5
+ ## 接入
6
+
7
+ ### 方式一:一条命令接入(推荐)
8
+
9
+ ```bash
10
+ npx @kioku-memory/cli connect zcode --server-url https://kioku.example.com
11
+ ```
12
+
13
+ 浏览器授权后自动写入 `~/.config/kioku/zcode.json`,并自动把内置插件目录注册到 ZCode 插件市场并启用 `kioku@kioku`。
14
+
15
+ ### 方式二:手动安装
16
+
17
+ 1. 写入地址与访问密钥:
18
+
19
+ ```bash
20
+ npx @kioku-memory/cli login zcode --server-url https://kioku.example.com
21
+ ```
22
+
23
+ (不想走浏览器授权时改用 `npx @kioku-memory/cli setup zcode --server-url https://kioku.example.com`。)
24
+
25
+ 2. 在终端注册并启用插件:
26
+
27
+ ```bash
28
+ git clone https://github.com/lonelyman0108/kioku-plugins
29
+ zcode plugins marketplace add /path/to/kioku-plugins/plugins/zcode
30
+ zcode plugins install kioku@kioku
31
+ zcode plugins enable kioku@kioku
32
+ ```
33
+
34
+ 3. 检查接入状态:
35
+
36
+ ```bash
37
+ npx @kioku-memory/cli doctor zcode
38
+ ```
39
+
40
+ ## 工作方式
41
+
42
+ - **配置来源**:地址与访问密钥保存在 `~/.config/kioku/zcode.json`(仅当前用户可读),不写入插件清单或命令行参数。
43
+ - **生命周期钩子(`hooks/hooks.json`)**:
44
+ - `SessionStart`(`startup|resume|clear`):向 Kioku 请求启动加载并以 `hookSpecificOutput.additionalContext` 注入。
45
+ - `UserPromptSubmit`:每轮输入按混合检索召回候选记忆,同时缓存本轮用户输入。
46
+ - `Stop`:将本轮用户输入与助手回复提交给 `turn.end` 提炼会话摘要(优先使用 `last_assistant_message`,缺失时回退读取 `transcript_path` 末尾 JSONL)。
47
+ - 任意服务或解析错误均静默放行(退出码 `0`、空标准输出),不阻塞正常对话。
48
+ - **MCP 记忆工具(`.mcp.json`)**:声明 `kioku` stdio 服务,由 `hooks/mcp-stdio.mjs` 转发 JSON-RPC 2.0 请求到 Kioku 的 `/v1/mcp` Streamable HTTP 端点。
@@ -0,0 +1,36 @@
1
+ #!/usr/bin/env node
2
+ // kioku 命令的入口,实现在 ../lib/kioku.mjs。插件启用期间,Claude Code 把插件的 bin/ 加进 Bash 工具的 PATH。
3
+ // 没有扩展名的文件按 CommonJS 还是 ES 模块执行,取决于 Node 的版本与上层的 package.json,
4
+ // 所以这里只用两边都能用的写法:动态 import,位置从 process.argv[1] 推
5
+ const load = (name) =>
6
+ Promise.all([import('node:fs'), import('node:path'), import('node:url')]).then(
7
+ ([fs, path, url]) => {
8
+ const lib = path.join(path.dirname(fs.realpathSync(process.argv[1])), '..', 'lib')
9
+ return import(url.pathToFileURL(path.join(lib, name)).href)
10
+ },
11
+ )
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
+
24
+ load('kioku.mjs')
25
+ .then((cli) => cli.main(process.argv.slice(2)))
26
+ .then((code) => {
27
+ process.exitCode = code
28
+ })
29
+ .catch((err) => {
30
+ process.exitCode = 2
31
+ // 只给错误类别:错误文字里可能带着环境变量的值。取不到共用的函数时只说一句固定的
32
+ return load('http.mjs').then(
33
+ ({ errorKind }) => process.stderr.write(`kioku:内部错误(${errorKind(err)})\n`),
34
+ () => process.stderr.write('kioku:内部错误\n'),
35
+ )
36
+ })
@@ -0,0 +1,350 @@
1
+ // ZCode 钩子:把 SessionStart、UserPromptSubmit、Stop 转发给 Kioku 的生命周期端点,
2
+ // 服务端返回的上下文以 hookSpecificOutput.additionalContext 交还 ZCode。
3
+ // 插件里不放提示词和格式逻辑,都由服务端决定。
4
+ // 任何失败都以退出码 0 结束、不写标准输出:记忆服务出问题不能挡住用户的输入。
5
+ // 服务地址与访问密钥来自 kioku login zcode / kioku setup zcode 写下的本机配置文件(~/.config/kioku/zcode.json)。
6
+ // 失败原因写到标准错误且不带访问密钥:不跟着跳转走,fetch 报错只取类别。
7
+
8
+ import { randomUUID } from 'node:crypto'
9
+ import {
10
+ chmod,
11
+ mkdir,
12
+ open,
13
+ readdir,
14
+ readFile,
15
+ rename,
16
+ rm,
17
+ stat,
18
+ writeFile,
19
+ } from 'node:fs/promises'
20
+ import { join } from 'node:path'
21
+
22
+ import { failureText, KiokuFailure } from '../lib/http.mjs'
23
+ import {
24
+ clip,
25
+ contextOf,
26
+ deviceKeyOf,
27
+ MAX_PROMPT,
28
+ MAX_REPLY,
29
+ MAX_SESSION_ID,
30
+ Misconfigured,
31
+ postEvent,
32
+ projectOf,
33
+ TIMEOUTS,
34
+ } from '../lib/lifecycle.mjs'
35
+ import { profileDir, readProfile } from '../lib/profile.mjs'
36
+
37
+ const HOOK_EVENTS = { 'session.start': 'SessionStart', 'prompt.submit': 'UserPromptSubmit' }
38
+ const NATIVE_TO_EVENT = {
39
+ SessionStart: 'session.start',
40
+ UserPromptSubmit: 'prompt.submit',
41
+ Stop: 'turn.end',
42
+ }
43
+ const ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/
44
+ const PENDING_PREFIX = 'turn.'
45
+ const PENDING_MAX_AGE = 24 * 60 * 60 * 1000
46
+ const TRANSCRIPT_TAIL = 2 * 1024 * 1024
47
+ const SETUP_HINT =
48
+ '运行 kioku login zcode 配置(没有 kioku 命令时用 npx @kioku-memory/cli login zcode)'
49
+
50
+ function pickString(value) {
51
+ return typeof value === 'string' ? value.trim() : ''
52
+ }
53
+
54
+ async function readStdin() {
55
+ if (process.stdin.isTTY) return ''
56
+ const chunks = []
57
+ for await (const chunk of process.stdin) chunks.push(chunk)
58
+ return Buffer.concat(chunks).toString('utf8')
59
+ }
60
+
61
+ // 只把上下文文本交给 ZCode,钩子输出的其他控制字段一律不透传
62
+ function writeContext(event, text) {
63
+ if (typeof text !== 'string' || !text) return
64
+ const hookEventName = HOOK_EVENTS[event]
65
+ if (!hookEventName) return
66
+ process.stdout.write(
67
+ JSON.stringify({
68
+ hookSpecificOutput: { hookEventName, additionalContext: text },
69
+ }),
70
+ )
71
+ }
72
+
73
+ function pendingDir(env) {
74
+ return join(
75
+ env.ZCODE_PLUGIN_DATA || env.PLUGIN_DATA || join(profileDir(env), 'zcode-state'),
76
+ 'turns',
77
+ )
78
+ }
79
+
80
+ function pendingTurnFile(env, sessionId, turnId) {
81
+ if (!ID.test(sessionId ?? '') || !ID.test(turnId ?? '')) return null
82
+ return join(pendingDir(env), `${PENDING_PREFIX}${sessionId}.id.${turnId}.json`)
83
+ }
84
+
85
+ function pendingLatestFile(env, sessionId) {
86
+ if (!ID.test(sessionId ?? '')) return null
87
+ return join(pendingDir(env), `${PENDING_PREFIX}${sessionId}.latest.json`)
88
+ }
89
+
90
+ async function atomicWriteJson(file, data) {
91
+ const temp = `${file}.${randomUUID()}.tmp`
92
+ try {
93
+ await writeFile(temp, JSON.stringify(data), { mode: 0o600, flag: 'wx' })
94
+ await chmod(temp, 0o600)
95
+ await rename(temp, file)
96
+ } catch (err) {
97
+ await rm(temp, { force: true }).catch(() => {})
98
+ throw err
99
+ }
100
+ }
101
+
102
+ async function savePending(env, sessionId, turnId, prompt, project) {
103
+ const exact = pendingTurnFile(env, sessionId, turnId)
104
+ const latest = pendingLatestFile(env, sessionId)
105
+ if (!exact && !latest) return
106
+ await mkdir(pendingDir(env), { recursive: true, mode: 0o700 })
107
+ const data = {
108
+ prompt,
109
+ ...(turnId ? { turnId } : {}),
110
+ ...(Object.keys(project ?? {}).length ? { project } : {}),
111
+ }
112
+ if (exact) await atomicWriteJson(exact, data)
113
+ if (latest) await atomicWriteJson(latest, data)
114
+ }
115
+
116
+ async function readPendingFile(file) {
117
+ if (!file) return null
118
+ try {
119
+ const parsed = JSON.parse(await readFile(file, 'utf8'))
120
+ if (typeof parsed?.prompt !== 'string' || !parsed.prompt) return null
121
+ return {
122
+ user: parsed.prompt,
123
+ turnId: typeof parsed.turnId === 'string' ? parsed.turnId : undefined,
124
+ project:
125
+ parsed.project && typeof parsed.project === 'object' && !Array.isArray(parsed.project)
126
+ ? parsed.project
127
+ : undefined,
128
+ }
129
+ } catch {
130
+ return null
131
+ }
132
+ }
133
+
134
+ async function takePending(env, sessionId, turnId) {
135
+ const exact = pendingTurnFile(env, sessionId, turnId)
136
+ const latest = pendingLatestFile(env, sessionId)
137
+ if (exact) {
138
+ const hit = await readPendingFile(exact)
139
+ await rm(exact, { force: true }).catch(() => {})
140
+ if (hit) {
141
+ const latestData = await readPendingFile(latest)
142
+ if (latest && latestData?.turnId === turnId) {
143
+ await rm(latest, { force: true }).catch(() => {})
144
+ }
145
+ return hit
146
+ }
147
+ }
148
+ if (latest) {
149
+ const hit = await readPendingFile(latest)
150
+ if (turnId && hit?.turnId && hit.turnId !== turnId) return null
151
+ await rm(latest, { force: true }).catch(() => {})
152
+ if (hit?.turnId) {
153
+ const hitExact = pendingTurnFile(env, sessionId, hit.turnId)
154
+ if (hitExact) await rm(hitExact, { force: true }).catch(() => {})
155
+ }
156
+ return hit
157
+ }
158
+ return null
159
+ }
160
+
161
+ async function sweepPending(env) {
162
+ const dir = pendingDir(env)
163
+ const names = await readdir(dir).catch(() => [])
164
+ for (const name of names) {
165
+ if (!name.startsWith(PENDING_PREFIX)) continue
166
+ const file = join(dir, name)
167
+ const age = Date.now() - ((await stat(file).catch(() => null))?.mtimeMs ?? Date.now())
168
+ if (age > PENDING_MAX_AGE) await rm(file, { force: true }).catch(() => {})
169
+ }
170
+ }
171
+
172
+ function textsOf(content) {
173
+ if (typeof content === 'string') return [content]
174
+ if (!Array.isArray(content)) return []
175
+ return content
176
+ .filter((block) => block?.type === 'text' && typeof block.text === 'string')
177
+ .map((block) => block.text)
178
+ }
179
+
180
+ function userText(entry) {
181
+ if (entry?.type !== 'user' || entry.isMeta || entry.isSidechain || entry.isCompactSummary) {
182
+ return null
183
+ }
184
+ const content = entry.message?.content ?? entry.content
185
+ if (Array.isArray(content) && content.some((block) => block?.type === 'tool_result')) return null
186
+ const text = textsOf(content).join('\n').trim()
187
+ return text || null
188
+ }
189
+
190
+ // 兜底从会话记录 JSONL 末尾读取最后一轮用户输入与助手回复
191
+ async function lastTurnFromTranscript(filePath) {
192
+ if (!filePath) return null
193
+ let handle
194
+ let text
195
+ try {
196
+ handle = await open(filePath, 'r')
197
+ const { size } = await handle.stat()
198
+ const start = Math.max(0, size - TRANSCRIPT_TAIL)
199
+ const len = size - start
200
+ if (len <= 0) return null
201
+ const buffer = Buffer.alloc(len)
202
+ const { bytesRead } = await handle.read(buffer, 0, len, start)
203
+ if (bytesRead <= 0) return null
204
+ text = buffer.subarray(0, bytesRead).toString('utf8')
205
+ if (start > 0) {
206
+ const nl = text.indexOf('\n')
207
+ text = nl >= 0 ? text.slice(nl + 1) : ''
208
+ }
209
+ } catch {
210
+ return null
211
+ } finally {
212
+ await handle?.close().catch(() => {})
213
+ }
214
+ const entries = []
215
+ for (const line of text.split('\n')) {
216
+ if (!line.trim()) continue
217
+ try {
218
+ entries.push(JSON.parse(line))
219
+ } catch {
220
+ // 忽略正在写入的不完整行
221
+ }
222
+ }
223
+ let at = entries.length - 1
224
+ while (at >= 0 && userText(entries[at]) === null) at--
225
+ if (at < 0) return null
226
+ const reply = entries
227
+ .slice(at + 1)
228
+ .filter((e) => e?.type === 'assistant' && !e.isSidechain)
229
+ .flatMap((e) => textsOf(e.message?.content ?? e.content))
230
+ .join('\n')
231
+ .trim()
232
+ return { user: userText(entries[at]), reply }
233
+ }
234
+
235
+ function resolveSessionId(input) {
236
+ return (
237
+ pickString(input.session_id) ||
238
+ pickString(input.conversation_id) ||
239
+ pickString(input.sessionId) ||
240
+ pickString(input.conversationId)
241
+ )
242
+ }
243
+
244
+ function resolveTurnId(input) {
245
+ return pickString(input.turn_id) || pickString(input.turnId)
246
+ }
247
+
248
+ function resolveEvent(argEvent, input) {
249
+ if (argEvent) return argEvent
250
+ const nativeName = pickString(input.hook_event_name) || pickString(input.hookEventName)
251
+ return NATIVE_TO_EVENT[nativeName] ?? ''
252
+ }
253
+
254
+ function noticeOf(err) {
255
+ return `Kioku 插件的配置无法使用,长期记忆不可用:${err.message}。${SETUP_HINT}。`
256
+ }
257
+
258
+ let resolvedEvent = process.argv[2] ?? ''
259
+
260
+ async function main(argEvent) {
261
+ const env = process.env
262
+ let input = {}
263
+ try {
264
+ const raw = await readStdin()
265
+ const parsed = raw.trim() ? JSON.parse(raw) : {}
266
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) input = parsed
267
+ } catch {
268
+ // 输入不是合法 JSON 时按空对象处理,不阻塞会话
269
+ }
270
+
271
+ const event = resolveEvent(argEvent, input)
272
+ resolvedEvent = event
273
+ const timeout = TIMEOUTS[event]
274
+ if (!timeout) throw new KiokuFailure(`未知事件 ${event}`)
275
+
276
+ if (event !== 'turn.end') await sweepPending(env)
277
+
278
+ let profile
279
+ try {
280
+ profile = await readProfile('zcode', env)
281
+ } catch (err) {
282
+ throw err instanceof KiokuFailure ? new Misconfigured(err.message, 'profile') : err
283
+ }
284
+ if (!profile) {
285
+ if (event === 'session.start') {
286
+ writeContext(event, `Kioku 插件尚未配置服务地址和访问密钥,长期记忆不可用:${SETUP_HINT}。`)
287
+ }
288
+ return
289
+ }
290
+
291
+ const { url: base, key } = profile
292
+ const explicitCwd = pickString(input.cwd)
293
+ const detectedProject = projectOf(explicitCwd || process.cwd())
294
+ const deviceKey = deviceKeyOf(env)
295
+ const rawSessionId = resolveSessionId(input)
296
+ const turnId = resolveTurnId(input)
297
+
298
+ const body = { event, ...(deviceKey ? { deviceKey } : {}) }
299
+ if (rawSessionId) body.sessionId = clip(rawSessionId, MAX_SESSION_ID)
300
+
301
+ if (event === 'turn.end') {
302
+ if (input.stop_hook_active === true || input.stopHookActive === true) return
303
+ const pending = await takePending(env, rawSessionId, turnId)
304
+ const directReply =
305
+ typeof input.last_assistant_message === 'string'
306
+ ? input.last_assistant_message
307
+ : typeof input.lastAssistantMessage === 'string'
308
+ ? input.lastAssistantMessage
309
+ : ''
310
+ const transcriptPath = pickString(input.transcript_path) || pickString(input.transcriptPath)
311
+ const transcriptTurn =
312
+ !pending?.user || !directReply.trim() ? await lastTurnFromTranscript(transcriptPath) : null
313
+ const user = pending?.user || transcriptTurn?.user || ''
314
+ const reply = directReply.trim() ? directReply.trim() : (transcriptTurn?.reply ?? '')
315
+ if (!body.sessionId || !user) return
316
+ const project = explicitCwd ? detectedProject : (pending?.project ?? detectedProject)
317
+ if (Object.keys(project).length) body.project = project
318
+ body.user = clip(user, MAX_PROMPT)
319
+ body.reply = clip(reply, MAX_REPLY)
320
+ await postEvent(base, key, body, timeout)
321
+ return
322
+ }
323
+
324
+ if (Object.keys(detectedProject).length) body.project = detectedProject
325
+ if (event === 'prompt.submit') {
326
+ const prompt = pickString(input.prompt)
327
+ if (!prompt) return
328
+ body.prompt = clip(prompt, MAX_PROMPT)
329
+ await savePending(env, rawSessionId, turnId, body.prompt, detectedProject).catch(() => {})
330
+ }
331
+
332
+ const res = await postEvent(base, key, body, timeout)
333
+ const { hostOutput } = await res.json()
334
+ writeContext(event, contextOf(hostOutput))
335
+ }
336
+
337
+ for (const stream of [process.stdout, process.stderr]) {
338
+ stream.on('error', (err) => {
339
+ if (!err || err.code !== 'EPIPE') throw err
340
+ })
341
+ }
342
+
343
+ const argEvent = process.argv[2]
344
+ main(argEvent).catch((err) => {
345
+ const activeEvent = resolvedEvent || argEvent || ''
346
+ if (activeEvent === 'session.start' && err instanceof Misconfigured) {
347
+ writeContext(activeEvent, noticeOf(err))
348
+ }
349
+ process.stderr.write(`Kioku ${activeEvent} 未生效:${failureText(err)}\n`)
350
+ })
@@ -0,0 +1,44 @@
1
+ {
2
+ "description": "会话开始时注入 Kioku 启动加载的内容,每轮输入时注入召回候选,每轮回复后把这一轮交给 Kioku 写会话摘要",
3
+ "hooks": {
4
+ "SessionStart": [
5
+ {
6
+ "matcher": "startup|resume|clear",
7
+ "hooks": [
8
+ {
9
+ "type": "process",
10
+ "command": "node",
11
+ "args": ["${ZCODE_PLUGIN_ROOT}/hooks/forward.mjs", "session.start"],
12
+ "timeoutMs": 10000,
13
+ "statusMessage": "读取 Kioku 的启动加载"
14
+ }
15
+ ]
16
+ }
17
+ ],
18
+ "UserPromptSubmit": [
19
+ {
20
+ "hooks": [
21
+ {
22
+ "type": "process",
23
+ "command": "node",
24
+ "args": ["${ZCODE_PLUGIN_ROOT}/hooks/forward.mjs", "prompt.submit"],
25
+ "timeoutMs": 10000,
26
+ "statusMessage": "召回 Kioku 相关记忆"
27
+ }
28
+ ]
29
+ }
30
+ ],
31
+ "Stop": [
32
+ {
33
+ "hooks": [
34
+ {
35
+ "type": "process",
36
+ "command": "node",
37
+ "args": ["${ZCODE_PLUGIN_ROOT}/hooks/forward.mjs", "turn.end"],
38
+ "timeoutMs": 10000
39
+ }
40
+ ]
41
+ }
42
+ ]
43
+ }
44
+ }