@kioku-memory/cli 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/LICENSE +202 -0
- package/NOTICE +7 -0
- package/README.md +151 -2
- package/bin/kioku +36 -0
- package/lib/api.mjs +35 -0
- package/lib/codex.mjs +309 -0
- package/lib/command.mjs +135 -0
- package/lib/config.mjs +50 -0
- package/lib/doctor.mjs +145 -0
- package/lib/dsh.mjs +75 -0
- package/lib/files.mjs +92 -0
- package/lib/hermes.mjs +261 -0
- package/lib/http.mjs +57 -0
- package/lib/import.mjs +262 -0
- package/lib/kioku.mjs +424 -0
- package/lib/lifecycle.mjs +118 -0
- package/lib/login.mjs +257 -0
- package/lib/mcp.mjs +142 -0
- package/lib/openclaw.mjs +248 -0
- package/lib/pi.mjs +81 -0
- package/lib/platforms.mjs +137 -0
- package/lib/profile.mjs +100 -0
- package/lib/redact.mjs +91 -0
- package/lib/secret.mjs +86 -0
- package/lib/setup.mjs +112 -0
- package/lib/sources.mjs +333 -0
- package/lib/target.mjs +62 -0
- package/lib/text.mjs +14 -0
- package/lib/usage.mjs +2 -0
- package/package.json +29 -4
package/lib/secret.mjs
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// 读访问密钥,不经过命令行参数(会进 shell 的历史与进程列表):先看 KIOKU_API_KEY,
|
|
2
|
+
// 标准输入不是终端时读它的全部内容,是终端时提示输入、不回显
|
|
3
|
+
|
|
4
|
+
import { StringDecoder } from 'node:string_decoder'
|
|
5
|
+
|
|
6
|
+
import { KiokuFailure } from './http.mjs'
|
|
7
|
+
|
|
8
|
+
async function readAll(stream) {
|
|
9
|
+
const chunks = []
|
|
10
|
+
for await (const chunk of stream) chunks.push(chunk)
|
|
11
|
+
return Buffer.concat(chunks).toString('utf8')
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// 终端发来的转义序列(方向键、粘贴的起止标记这类):不是输入的内容
|
|
15
|
+
// eslint-disable-next-line no-control-regex
|
|
16
|
+
const ESCAPES = /\u001b(?:\[[0-9;?]*[ -/]*[@-~]|O.|.)?/g
|
|
17
|
+
|
|
18
|
+
// 把终端发来的一段字符并进已经输入的内容,返回 { value, done }:done 为 'enter' 是输完了,'cancel' 是取消。
|
|
19
|
+
// 回车结束,Ctrl-C、Ctrl-D 取消,退格删掉一个字,Ctrl-U 清空;别的控制字符与转义序列不算输入
|
|
20
|
+
export function applyKeys(value, text) {
|
|
21
|
+
let chars = Array.from(value)
|
|
22
|
+
for (const char of text.replace(ESCAPES, '')) {
|
|
23
|
+
if (char === '\r' || char === '\n') return { value: chars.join(''), done: 'enter' }
|
|
24
|
+
if (char === '\u0003' || char === '\u0004') return { value: '', done: 'cancel' }
|
|
25
|
+
if (char === '\u007f' || char === '\b') chars.pop()
|
|
26
|
+
else if (char === '\u0015') chars = []
|
|
27
|
+
else if (!/\p{Cc}/u.test(char)) chars.push(char)
|
|
28
|
+
}
|
|
29
|
+
return { value: chars.join(''), done: null }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// 在终端里读一行,不回显。不管怎么结束都把终端改回原来的模式
|
|
33
|
+
function readHidden(stdin, out, label) {
|
|
34
|
+
return new Promise((resolve, reject) => {
|
|
35
|
+
let value = ''
|
|
36
|
+
// 一个字可能被切在两块里:按 UTF-8 接着解码
|
|
37
|
+
const decoder = new StringDecoder('utf8')
|
|
38
|
+
const finish = (fn, arg) => {
|
|
39
|
+
stdin.off('data', onData)
|
|
40
|
+
stdin.off('end', onEnd)
|
|
41
|
+
stdin.off('error', onError)
|
|
42
|
+
try {
|
|
43
|
+
stdin.setRawMode(false)
|
|
44
|
+
} catch {
|
|
45
|
+
// 终端已经没了
|
|
46
|
+
}
|
|
47
|
+
stdin.pause()
|
|
48
|
+
out.write('\n')
|
|
49
|
+
fn(arg)
|
|
50
|
+
}
|
|
51
|
+
const onData = (chunk) => {
|
|
52
|
+
const result = applyKeys(value, decoder.write(chunk))
|
|
53
|
+
value = result.value
|
|
54
|
+
if (result.done === 'enter') finish(resolve, value)
|
|
55
|
+
else if (result.done === 'cancel') finish(reject, new KiokuFailure('已取消'))
|
|
56
|
+
}
|
|
57
|
+
// 终端挂断:按取消算,不拿半截的输入当访问密钥
|
|
58
|
+
const onEnd = () => finish(reject, new KiokuFailure('输入中断了,没有读到访问密钥'))
|
|
59
|
+
const onError = () => finish(reject, new KiokuFailure('无法从终端读取访问密钥'))
|
|
60
|
+
out.write(label)
|
|
61
|
+
stdin.setRawMode(true)
|
|
62
|
+
stdin.resume()
|
|
63
|
+
stdin.on('data', onData)
|
|
64
|
+
stdin.on('end', onEnd)
|
|
65
|
+
stdin.on('error', onError)
|
|
66
|
+
})
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// 没有给访问密钥时返回空字符串
|
|
70
|
+
export async function readSecret({
|
|
71
|
+
env = process.env,
|
|
72
|
+
stdin = process.stdin,
|
|
73
|
+
out = process.stderr,
|
|
74
|
+
canLogin = false,
|
|
75
|
+
hasSaved = false,
|
|
76
|
+
} = {}) {
|
|
77
|
+
const fromEnv = (env.KIOKU_API_KEY ?? '').trim()
|
|
78
|
+
if (fromEnv) return fromEnv
|
|
79
|
+
if (!stdin.isTTY) return (await readAll(stdin)).trim()
|
|
80
|
+
const label = hasSaved
|
|
81
|
+
? '访问密钥(不回显;直接回车沿用上次的):'
|
|
82
|
+
: canLogin
|
|
83
|
+
? '访问密钥(不回显;直接回车改用浏览器授权):'
|
|
84
|
+
: '访问密钥(不回显):'
|
|
85
|
+
return (await readHidden(stdin, out, label)).trim()
|
|
86
|
+
}
|
package/lib/setup.mjs
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// kioku setup:把平台交给 Kioku 接管。平台有自己的一套步骤时(codex)交给它,否则按下面通用的做法:
|
|
2
|
+
// 停用平台自带的长期记忆,只改平台的用户设置里的那几项,
|
|
3
|
+
// 改之前显示要改什么、留一份备份;--undo 只把这几项改回去,不动设置里的其他内容(文件会按 JSON 重新排版)
|
|
4
|
+
|
|
5
|
+
import { readSettings, writeSettings } from './files.mjs'
|
|
6
|
+
import { deviceLogin } from './login.mjs'
|
|
7
|
+
import { plain } from './text.mjs'
|
|
8
|
+
import { platformNames, PLATFORMS } from './platforms.mjs'
|
|
9
|
+
import { readSecret } from './secret.mjs'
|
|
10
|
+
import { UsageError } from './usage.mjs'
|
|
11
|
+
|
|
12
|
+
export { readSettings, writeSettings }
|
|
13
|
+
|
|
14
|
+
export const SETUP_USAGE = `用法:kioku setup <平台> [--dry-run] [--undo] [--server-url <地址>] [--no-check]
|
|
15
|
+
|
|
16
|
+
把平台交给 Kioku 接管:停用平台自带的长期记忆;没有自己的密钥存储的平台(codex、pi、hermes、openclaw、dsh)再写下服务地址与访问密钥。
|
|
17
|
+
|
|
18
|
+
<平台> ${platformNames()}
|
|
19
|
+
--dry-run 只显示要改什么,不写文件
|
|
20
|
+
--undo 改回去:重新启用平台自带的长期记忆,删掉写下的地址与访问密钥
|
|
21
|
+
--server-url <地址> Kioku 的服务地址,例如 https://kioku.example.com(codex、pi、hermes、openclaw、dsh 用;也可以用 KIOKU_SERVER_URL)
|
|
22
|
+
--no-check 不先连一次 Kioku 核对地址与访问密钥(codex、pi、hermes、openclaw、dsh 用)
|
|
23
|
+
|
|
24
|
+
访问密钥不写在命令行上:从 KIOKU_API_KEY 读,或者从标准输入读;在终端里运行时会提示输入(不回显),
|
|
25
|
+
直接回车就改用浏览器授权(同 kioku login)。
|
|
26
|
+
只改平台设置里和 Kioku 有关的几项,第一次改之前把原来的文件备份成同目录下的 <文件名>.kioku-backup(已有备份时不覆盖)。
|
|
27
|
+
改完新开会话生效。本地已有的记忆文件不会被删掉。
|
|
28
|
+
`
|
|
29
|
+
|
|
30
|
+
// 给各平台的 setup 用的浏览器授权:按平台的运行时申请
|
|
31
|
+
function browserLogin(out) {
|
|
32
|
+
return ({ url, id }) => deviceLogin({ url, runtimeFamily: PLATFORMS[id].runtimeFamily }, { out })
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function parseSetupArgs(argv) {
|
|
36
|
+
const options = { dryRun: false, undo: false, check: true, serverUrl: undefined }
|
|
37
|
+
const names = []
|
|
38
|
+
for (let i = 0; i < argv.length; i++) {
|
|
39
|
+
const arg = argv[i]
|
|
40
|
+
if (arg === '--dry-run') options.dryRun = true
|
|
41
|
+
else if (arg === '--undo') options.undo = true
|
|
42
|
+
else if (arg === '--no-check') options.check = false
|
|
43
|
+
else if (arg === '--server-url') {
|
|
44
|
+
options.serverUrl = argv[++i]
|
|
45
|
+
if (!options.serverUrl) throw new UsageError('--server-url 后面要写地址')
|
|
46
|
+
} else if (arg.startsWith('-')) throw new UsageError(`不认识的选项 ${arg}`)
|
|
47
|
+
else names.push(arg)
|
|
48
|
+
}
|
|
49
|
+
if (names.length !== 1) throw new UsageError('要写一个平台')
|
|
50
|
+
if (!Object.hasOwn(PLATFORMS, names[0])) {
|
|
51
|
+
throw new UsageError(`不认识的平台 ${names[0]},可以用的:${platformNames()}`)
|
|
52
|
+
}
|
|
53
|
+
const platform = PLATFORMS[names[0]]
|
|
54
|
+
if (!platform.setup && (options.serverUrl !== undefined || !options.check)) {
|
|
55
|
+
throw new UsageError(
|
|
56
|
+
`${platform.name} 的地址与访问密钥在它自己的插件配置里填,不用 --server-url、--no-check`,
|
|
57
|
+
)
|
|
58
|
+
}
|
|
59
|
+
return { ...options, platform: names[0] }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function shown(value) {
|
|
63
|
+
return value === undefined ? '(未设置)' : JSON.stringify(value)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export async function setup(
|
|
67
|
+
argv,
|
|
68
|
+
{
|
|
69
|
+
env = process.env,
|
|
70
|
+
out = process.stdout,
|
|
71
|
+
cwd = process.cwd(),
|
|
72
|
+
readKey = readSecret,
|
|
73
|
+
// 在终端里运行、没给访问密钥时可以改用浏览器授权;不在终端里(管道、agent 的命令)时没有;传 null 是明说不要
|
|
74
|
+
login = process.stdin.isTTY ? browserLogin(out) : null,
|
|
75
|
+
} = {},
|
|
76
|
+
) {
|
|
77
|
+
const options = parseSetupArgs(argv)
|
|
78
|
+
const { platform: id, dryRun, undo } = options
|
|
79
|
+
const platform = PLATFORMS[id]
|
|
80
|
+
// 有自己的一套步骤的平台
|
|
81
|
+
if (platform.setup) return platform.setup(options, { env, out, cwd, readKey, plain, login })
|
|
82
|
+
const { memory } = platform
|
|
83
|
+
const file = platform.settingsFile(env)
|
|
84
|
+
const { settings, text } = await readSettings(file)
|
|
85
|
+
const next = undo ? memory.restore(settings) : memory.disable(settings)
|
|
86
|
+
const changes = memory.changed.filter(
|
|
87
|
+
(key) => JSON.stringify(settings[key]) !== JSON.stringify(next[key]),
|
|
88
|
+
)
|
|
89
|
+
const goal = undo ? '已启用' : '已停用'
|
|
90
|
+
if (!changes.length) {
|
|
91
|
+
out.write(`${platform.name} 的${memory.name}${goal},${file} 不用改\n`)
|
|
92
|
+
} else {
|
|
93
|
+
out.write(`${file}\n`)
|
|
94
|
+
for (const key of changes) {
|
|
95
|
+
out.write(` ${key}:${shown(settings[key])} → ${shown(next[key])}\n`)
|
|
96
|
+
}
|
|
97
|
+
if (dryRun) {
|
|
98
|
+
out.write('没有写入(--dry-run)\n')
|
|
99
|
+
return 0
|
|
100
|
+
}
|
|
101
|
+
const backedUp = await writeSettings(file, next, text)
|
|
102
|
+
if (backedUp) out.write(`原来的设置备份在 ${file}.kioku-backup\n`)
|
|
103
|
+
else if (text !== null) out.write(`${file}.kioku-backup 已有更早的备份,没有覆盖\n`)
|
|
104
|
+
out.write(`${platform.name} 的${memory.name}${goal},新开会话生效\n`)
|
|
105
|
+
}
|
|
106
|
+
// 别处也停用着时,改回设置并不能重新启用它;别处又启用了时,停用也不生效
|
|
107
|
+
const by = undo ? memory.disabledBy(next, env) : null
|
|
108
|
+
if (by) out.write(`注意:${by}仍然停用着它\n`)
|
|
109
|
+
const again = undo ? null : await memory.enabledBy(env, cwd)
|
|
110
|
+
if (again) out.write(`注意:${again}又启用了它,要在那里一起改\n`)
|
|
111
|
+
return 0
|
|
112
|
+
}
|
package/lib/sources.mjs
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
// kioku import 认得的来源:各平台自带的长期记忆放在哪、是什么格式、迁进 Kioku 时放到哪个坐标。
|
|
2
|
+
// 这里只读文件、出条目,不发请求。指令文件(AGENTS.md、CLAUDE.md)不是记忆,不在这里
|
|
3
|
+
|
|
4
|
+
import { createHash } from 'node:crypto'
|
|
5
|
+
import { lstat, readdir, readFile, stat } from 'node:fs/promises'
|
|
6
|
+
import { homedir } from 'node:os'
|
|
7
|
+
import { basename, dirname, join, resolve } from 'node:path'
|
|
8
|
+
|
|
9
|
+
// 与服务端 contracts 的上限一致
|
|
10
|
+
const MAX_CONTENT = 20_000
|
|
11
|
+
const MAX_TITLE = 80
|
|
12
|
+
const MAX_DISCLOSURE = 500
|
|
13
|
+
const MAX_SEGMENT = 64
|
|
14
|
+
// 一个来源最多读这么多个文件:指错了目录时不把整个盘读一遍
|
|
15
|
+
const MAX_FILES = 2000
|
|
16
|
+
|
|
17
|
+
// 坐标里的一段:小写字母、数字、_ 与 -。别的字符换成 -;什么都不剩(例如全是中文)时用内容的摘要
|
|
18
|
+
export function segment(text) {
|
|
19
|
+
const slug = String(text ?? '')
|
|
20
|
+
.toLowerCase()
|
|
21
|
+
.replace(/[^a-z0-9_-]+/g, '-')
|
|
22
|
+
.replace(/-{2,}/g, '-')
|
|
23
|
+
.replace(/^-+|-+$/g, '')
|
|
24
|
+
.slice(0, MAX_SEGMENT)
|
|
25
|
+
.replace(/-+$/g, '')
|
|
26
|
+
if (slug) return slug
|
|
27
|
+
return `m-${createHash('sha256')
|
|
28
|
+
.update(String(text ?? ''))
|
|
29
|
+
.digest('hex')
|
|
30
|
+
.slice(0, 10)}`
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// 标题:压成一行,去掉控制字符,按码点截断
|
|
34
|
+
export function titleOf(text) {
|
|
35
|
+
const line = String(text ?? '')
|
|
36
|
+
.replace(/\p{Cc}+/gu, ' ')
|
|
37
|
+
.trim()
|
|
38
|
+
return Array.from(line).slice(0, MAX_TITLE).join('')
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function clipped(text, max) {
|
|
42
|
+
return Array.from(String(text ?? '').trim())
|
|
43
|
+
.slice(0, max)
|
|
44
|
+
.join('')
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// 文件开头用 --- 括起来的那一段,只认「键: 值」和缩进一层的「键: 值」(Claude Code 的记忆文件就这么多);
|
|
48
|
+
// 缩进更深的、多行写法(> 与 |)的值不认。返回 { meta, body }:
|
|
49
|
+
// - 不是以单独一行 --- 开头,或者里面有不像键值的行:没有文件头,body 是全文(以分隔线开头的普通 Markdown)
|
|
50
|
+
// - 像文件头却找不到单独一行的 --- 结尾:unterminated 为真,调用方不要把它当正文发出去
|
|
51
|
+
export function frontmatter(text) {
|
|
52
|
+
const whole = text.replace(/^\uFEFF/, '')
|
|
53
|
+
const lines = whole.split(/\r?\n/)
|
|
54
|
+
const plainBody = { meta: {}, body: whole }
|
|
55
|
+
if (lines[0]?.trimEnd() !== '---') return plainBody
|
|
56
|
+
const meta = {}
|
|
57
|
+
let parent = null
|
|
58
|
+
let childIndent = null
|
|
59
|
+
// 上一个键用的是多行写法:后面缩进的行是它的值,跳过
|
|
60
|
+
let block = false
|
|
61
|
+
let keys = 0
|
|
62
|
+
for (let i = 1; i < lines.length; i++) {
|
|
63
|
+
const line = lines[i]
|
|
64
|
+
if (line.trimEnd() === '---') {
|
|
65
|
+
return { meta, body: lines.slice(i + 1).join('\n') }
|
|
66
|
+
}
|
|
67
|
+
if (!line.trim()) continue
|
|
68
|
+
if (block && /^\s/.test(line)) continue
|
|
69
|
+
const pair = /^(\s*)([A-Za-z_][\w-]*):\s*(.*)$/.exec(line)
|
|
70
|
+
// 不像键值的行:前面一个键都没有的话这不是文件头;已经有键了就是文件头没写完
|
|
71
|
+
if (!pair) return keys ? { meta, body: '', unterminated: true } : plainBody
|
|
72
|
+
keys++
|
|
73
|
+
const indent = pair[1].length
|
|
74
|
+
const raw = pair[3].trim()
|
|
75
|
+
block = /^[>|][+-]?$/.test(raw)
|
|
76
|
+
// 多行写法的标记不是值
|
|
77
|
+
const value = block ? '' : raw.replace(/^(["'])(.*)\1$/, '$2')
|
|
78
|
+
if (indent === 0) {
|
|
79
|
+
meta[pair[2]] = value
|
|
80
|
+
parent = raw === '' ? pair[2] : null
|
|
81
|
+
childIndent = null
|
|
82
|
+
} else if (parent) {
|
|
83
|
+
// 只收紧挨着的那一层:更深的缩进是下一层的,不摊到这一层上
|
|
84
|
+
childIndent ??= indent
|
|
85
|
+
if (indent === childIndent) meta[`${parent}.${pair[2]}`] = value
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return { meta, body: '', unterminated: true }
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// 一份 Markdown 拆成几条:有只写着一个分节号(U+00A7,Hermes 用它隔开各条)的行就按它拆,否则按二级标题拆,都没有就是一整条。
|
|
92
|
+
// 每条是 { heading, text },heading 可能没有
|
|
93
|
+
export function sections(text) {
|
|
94
|
+
const body = text.replace(/^\uFEFF/, '')
|
|
95
|
+
if (/^\u00a7\s*$/m.test(body)) {
|
|
96
|
+
return body
|
|
97
|
+
.split(/^\u00a7\s*$/m)
|
|
98
|
+
.map((part) => ({ heading: null, text: part.trim() }))
|
|
99
|
+
.filter((part) => part.text)
|
|
100
|
+
}
|
|
101
|
+
const parts = []
|
|
102
|
+
let current = { heading: null, lines: [] }
|
|
103
|
+
for (const line of body.split(/\r?\n/)) {
|
|
104
|
+
const heading = /^##\s+(.+?)\s*#*\s*$/.exec(line)
|
|
105
|
+
if (heading) {
|
|
106
|
+
parts.push(current)
|
|
107
|
+
current = { heading: heading[1], lines: [line] }
|
|
108
|
+
} else current.lines.push(line)
|
|
109
|
+
}
|
|
110
|
+
parts.push(current)
|
|
111
|
+
return parts
|
|
112
|
+
.map((part) => ({ heading: part.heading, text: part.lines.join('\n').trim() }))
|
|
113
|
+
.filter((part) => part.text)
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// 条目:{ source, uri, title, content, disclosure },或者 { source, skipped: 原因 }
|
|
117
|
+
function entry(source, { uri, title, content, disclosure }) {
|
|
118
|
+
const text = content.trim()
|
|
119
|
+
if (!text) return { source, skipped: '没有内容' }
|
|
120
|
+
if (Array.from(text).length > MAX_CONTENT) {
|
|
121
|
+
return { source, skipped: `正文超过 ${MAX_CONTENT} 个字,拆开后再导入` }
|
|
122
|
+
}
|
|
123
|
+
const item = { source, uri, title: titleOf(title) || basename(source), content: text }
|
|
124
|
+
const hint = clipped(disclosure, MAX_DISCLOSURE)
|
|
125
|
+
return hint ? { ...item, disclosure: hint } : item
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// 一个记忆文件最多这么大(字节):正文上限是 2 万字,再大的不读进内存
|
|
129
|
+
const MAX_FILE_BYTES = 512 * 1024
|
|
130
|
+
|
|
131
|
+
// 读一个记忆文件的文字。只读普通文件:符号链接不跟(它可以指到记忆目录之外的任何文件,读出来就发给服务端了),
|
|
132
|
+
// 管道、设备这类也不读;太大的、不是文本的不读。读得了返回 { text },读不了返回 { problem };没有这个文件返回 null
|
|
133
|
+
async function readable(file) {
|
|
134
|
+
const info = await lstat(file).catch(() => null)
|
|
135
|
+
if (!info) return null
|
|
136
|
+
if (info.isSymbolicLink()) return { problem: '是符号链接,不读' }
|
|
137
|
+
if (!info.isFile()) return { problem: '不是普通文件' }
|
|
138
|
+
if (info.size > MAX_FILE_BYTES) return { problem: '文件太大,不读' }
|
|
139
|
+
let text
|
|
140
|
+
try {
|
|
141
|
+
text = await readFile(file, 'utf8')
|
|
142
|
+
} catch {
|
|
143
|
+
return { problem: '读不了这个文件' }
|
|
144
|
+
}
|
|
145
|
+
// 带着空字符或解码不了的字节(成了替换字符)的不是文本
|
|
146
|
+
if (text.includes('\0') || text.includes('\uFFFD')) return { problem: '不是文本文件' }
|
|
147
|
+
return { text }
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// 是不是真的目录(不是指向别处的符号链接)
|
|
151
|
+
async function isRealDir(dir) {
|
|
152
|
+
return (await lstat(dir).catch(() => null))?.isDirectory() ?? false
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
async function markdownFiles(dir) {
|
|
156
|
+
const names = await readdir(dir).catch(() => [])
|
|
157
|
+
return names.filter((name) => name.toLowerCase().endsWith('.md')).sort()
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// 坐标里的一段,从末尾取:太长时留后面的(路径越靠后越能区分)
|
|
161
|
+
function tailSegment(text) {
|
|
162
|
+
const slug = segment(text.length > MAX_SEGMENT ? text.slice(-MAX_SEGMENT) : text)
|
|
163
|
+
return slug.replace(/^-+/, '') || segment(text)
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// Claude Code 把项目目录的路径编码成目录名(斜杠等换成 -),还原不回去。
|
|
167
|
+
// 去掉开头的主目录与常见的上级目录,剩下的当项目名:坐标里要的是认得出的名字,不是整段路径。
|
|
168
|
+
// 代价是分不清的情况会得到同一个名字(~/code/dev-proxy 与 ~/code/proxy):这时两个项目里同名的记忆落到同一个坐标,
|
|
169
|
+
// 计划里会列出来,不会悄悄顶掉。主目录对不上时(换了机器、换了用户)项目名会带着整段路径
|
|
170
|
+
const CONTAINERS =
|
|
171
|
+
/^(documents|desktop|code|projects|project|src|work|workspace|dev|repos|git|github)-/i
|
|
172
|
+
export function claudeProjectName(encoded, home = homedir()) {
|
|
173
|
+
const prefix = home.replace(/[^A-Za-z0-9]/g, '-')
|
|
174
|
+
// 前缀之后要正好是一段的开头,/Users/lm 不能去掉 -Users-lmx-… 的开头
|
|
175
|
+
let rest = encoded.startsWith(`${prefix}-`) ? encoded.slice(prefix.length + 1) : encoded
|
|
176
|
+
rest = rest.replace(/^-+/, '')
|
|
177
|
+
while (CONTAINERS.test(rest)) rest = rest.replace(CONTAINERS, '')
|
|
178
|
+
return tailSegment(rest || encoded)
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// Claude Code 的自动记忆:<配置目录>/projects/<项目>/memory/*.md,一个文件一条,文件头里有名字、说明与类型。
|
|
182
|
+
// MEMORY.md 是索引,不是记忆。类型决定放到哪,都带着项目名(不同项目里同名的不互相顶掉):
|
|
183
|
+
// - user(用户是谁、偏好)→ 本人的 about;project(项目的事)、reference(外部资料在哪)→ 本人下按项目放
|
|
184
|
+
// - feedback(该怎么干活)→ 这个应用下按项目放:别的 agent 用不上
|
|
185
|
+
async function claudeCode({ env, path, app }) {
|
|
186
|
+
// 先变成绝对路径:相对路径取上一级的名字会取到 . 或 ..
|
|
187
|
+
const root = resolve(
|
|
188
|
+
path ?? join(env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude'), 'projects'),
|
|
189
|
+
)
|
|
190
|
+
const info = await stat(root).catch(() => null)
|
|
191
|
+
if (!info?.isDirectory()) return { root, found: false, entries: [] }
|
|
192
|
+
// 给的是某个项目的 memory 目录时只读它,否则读每个项目的
|
|
193
|
+
const direct = (await markdownFiles(root)).length > 0
|
|
194
|
+
const projects = direct
|
|
195
|
+
? [{ name: claudeProjectName(basename(dirname(root))), dir: root }]
|
|
196
|
+
: (await readdir(root).catch(() => []))
|
|
197
|
+
.sort()
|
|
198
|
+
.map((name) => ({ name: claudeProjectName(name), dir: join(root, name, 'memory') }))
|
|
199
|
+
const entries = []
|
|
200
|
+
for (const project of projects) {
|
|
201
|
+
// 项目的 memory 目录是符号链接时不进去
|
|
202
|
+
if (!direct && !(await isRealDir(project.dir))) continue
|
|
203
|
+
for (const name of await markdownFiles(project.dir)) {
|
|
204
|
+
if (name === 'MEMORY.md') continue
|
|
205
|
+
if (entries.length >= MAX_FILES) break
|
|
206
|
+
const source = join(project.dir, name)
|
|
207
|
+
const read = await readable(source)
|
|
208
|
+
if (!read) continue
|
|
209
|
+
if (read.problem) {
|
|
210
|
+
entries.push({ source, skipped: read.problem })
|
|
211
|
+
continue
|
|
212
|
+
}
|
|
213
|
+
const { meta, body, unterminated } = frontmatter(read.text)
|
|
214
|
+
if (unterminated) {
|
|
215
|
+
entries.push({ source, skipped: '文件头没有结尾的 ---,分不清哪些是正文' })
|
|
216
|
+
continue
|
|
217
|
+
}
|
|
218
|
+
const id = segment(meta.name || name.replace(/\.md$/i, ''))
|
|
219
|
+
const type = meta['metadata.type'] || meta.type || ''
|
|
220
|
+
const uri =
|
|
221
|
+
type === 'user'
|
|
222
|
+
? `user://about/${project.name}/${id}`
|
|
223
|
+
: type === 'feedback'
|
|
224
|
+
? `app://${app}/feedback/${project.name}/${id}`
|
|
225
|
+
: type === 'reference'
|
|
226
|
+
? `user://reference/${project.name}/${id}`
|
|
227
|
+
: `user://projects/${project.name}/${id}`
|
|
228
|
+
entries.push(
|
|
229
|
+
entry(source, {
|
|
230
|
+
uri,
|
|
231
|
+
title: meta.description || meta.name || name,
|
|
232
|
+
content: body,
|
|
233
|
+
disclosure: meta.description,
|
|
234
|
+
}),
|
|
235
|
+
)
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
return { root, found: true, entries }
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// 一段文字的摘要,做坐标里的标识:内容不变标识就不变
|
|
242
|
+
function digest(text) {
|
|
243
|
+
return `m-${createHash('sha256').update(text).digest('hex').slice(0, 10)}`
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// 一组「文件 → 放到哪」的来源:每个文件按 sections 拆成几条。标识取小节标题;没有标题的、标题重了的取内容的摘要,
|
|
247
|
+
// 不按顺序编号:文件里插一条、删一条之后,别的条的坐标不能跟着变,否则去重就认不出它们了。
|
|
248
|
+
// 代价是没有标题的一段改了内容就是新的一条,旧的留在 Kioku 里
|
|
249
|
+
async function fromFiles(root, files) {
|
|
250
|
+
const info = await stat(root).catch(() => null)
|
|
251
|
+
if (!info?.isDirectory()) return { root, found: false, entries: [] }
|
|
252
|
+
const entries = []
|
|
253
|
+
for (const { file, prefix, title, single } of files) {
|
|
254
|
+
const source = join(root, file)
|
|
255
|
+
const read = await readable(source)
|
|
256
|
+
if (!read) continue
|
|
257
|
+
if (read.problem) {
|
|
258
|
+
entries.push({ source, skipped: read.problem })
|
|
259
|
+
continue
|
|
260
|
+
}
|
|
261
|
+
const parts = single ? [{ heading: null, text: read.text.trim() }] : sections(read.text)
|
|
262
|
+
const used = new Set()
|
|
263
|
+
parts.forEach((part, index) => {
|
|
264
|
+
let id = part.heading ? segment(part.heading) : digest(part.text)
|
|
265
|
+
if (used.has(id)) id = digest(part.text)
|
|
266
|
+
used.add(id)
|
|
267
|
+
entries.push(
|
|
268
|
+
entry(parts.length > 1 ? `${source}(第 ${index + 1} 段)` : source, {
|
|
269
|
+
uri: single ? prefix : `${prefix}/${id}`,
|
|
270
|
+
title: part.heading || title,
|
|
271
|
+
content: part.text,
|
|
272
|
+
}),
|
|
273
|
+
)
|
|
274
|
+
})
|
|
275
|
+
}
|
|
276
|
+
return { root, found: true, entries }
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// Hermes:<主目录>/.hermes/memories 下的 MEMORY.md(agent 自己记的)与 USER.md(用户画像)。
|
|
280
|
+
// 坐标里带着来源的名字:几个来源迁进同一个应用时不落到一起
|
|
281
|
+
function hermes({ env, path, app }) {
|
|
282
|
+
const root = resolve(path ?? join(env.HERMES_HOME || join(homedir(), '.hermes'), 'memories'))
|
|
283
|
+
return fromFiles(root, [
|
|
284
|
+
{ file: 'MEMORY.md', prefix: `app://${app}/hermes/notes`, title: 'Hermes 的记忆' },
|
|
285
|
+
{ file: 'USER.md', prefix: 'user://about/hermes', title: 'Hermes 记下的用户画像' },
|
|
286
|
+
])
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
// OpenClaw:工作区下的 MEMORY.md、USER.md,以及 memory/ 里按日期的笔记(一个文件整个当一条)。
|
|
290
|
+
// OPENCLAW_HOME 换的是主目录,工作区默认在它下面的 .openclaw/workspace;配置里改过工作区位置的用 --path 指明
|
|
291
|
+
async function openclaw({ env, path, app }) {
|
|
292
|
+
const root = resolve(path ?? join(env.OPENCLAW_HOME || homedir(), '.openclaw', 'workspace'))
|
|
293
|
+
const notes = join(root, 'memory')
|
|
294
|
+
const daily = ((await isRealDir(notes)) ? await markdownFiles(notes) : [])
|
|
295
|
+
// 一天可以有几个:2026-11-10.md,或者带后缀的 2026-11-10-<名字>.md
|
|
296
|
+
.filter((name) => /^\d{4}-\d{2}-\d{2}(-[A-Za-z0-9][A-Za-z0-9-]*)?\.md$/.test(name))
|
|
297
|
+
.slice(0, MAX_FILES)
|
|
298
|
+
.map((name) => {
|
|
299
|
+
const stem = name.slice(0, -3)
|
|
300
|
+
const suffix = stem.slice(11)
|
|
301
|
+
return {
|
|
302
|
+
file: join('memory', name),
|
|
303
|
+
// 和别的来源一样规整成坐标里的一段(长度、连着的连字符);只差大小写的两个文件会落到同一个坐标,
|
|
304
|
+
// 后一个在计划里按撞名列出来
|
|
305
|
+
prefix: `app://${app}/openclaw/journal/${segment(stem)}`,
|
|
306
|
+
title: suffix ? `${stem.slice(0, 10)} 的笔记(${suffix})` : `${stem} 的笔记`,
|
|
307
|
+
single: true,
|
|
308
|
+
}
|
|
309
|
+
})
|
|
310
|
+
return fromFiles(root, [
|
|
311
|
+
{ file: 'MEMORY.md', prefix: `app://${app}/openclaw/notes`, title: 'OpenClaw 的记忆' },
|
|
312
|
+
{ file: 'USER.md', prefix: 'user://about/openclaw', title: 'OpenClaw 记下的用户画像' },
|
|
313
|
+
...daily,
|
|
314
|
+
])
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
export const SOURCES = {
|
|
318
|
+
'claude-code': { name: 'Claude Code 的自动记忆', read: claudeCode },
|
|
319
|
+
hermes: { name: 'Hermes 的记忆文件', read: hermes },
|
|
320
|
+
openclaw: { name: 'OpenClaw 工作区的记忆文件', read: openclaw },
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// 认得、但迁不了的来源,说明原因
|
|
324
|
+
export const UNSUPPORTED_SOURCES = {
|
|
325
|
+
codex:
|
|
326
|
+
'Codex 自带的 Memories 存在它自己的数据库里,格式没有公开,迁不了;它在本地默认是关着的,多半没有内容',
|
|
327
|
+
pi: 'pi 没有自带的长期记忆',
|
|
328
|
+
dsh: 'DeepSeek Harness 没有自带的长期记忆',
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
export function sourceNames() {
|
|
332
|
+
return Object.keys(SOURCES).join('、')
|
|
333
|
+
}
|
package/lib/target.mjs
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// kioku setup 给没有自己的密钥存储的平台定下要用的服务地址与访问密钥:这次给的优先,没给的沿用上次写下的;
|
|
2
|
+
// 先看格式,再连一次 Kioku 核对,都过了才轮到各平台去写文件
|
|
3
|
+
|
|
4
|
+
import { whoami } from './api.mjs'
|
|
5
|
+
import { keyFormatError, KiokuFailure } from './http.mjs'
|
|
6
|
+
import { readProfile, serverUrlProblem } from './profile.mjs'
|
|
7
|
+
import { UsageError } from './usage.mjs'
|
|
8
|
+
|
|
9
|
+
// 服务地址:这次给的、环境变量里的、上次写下的,依次取;没有、格式不对时抛错
|
|
10
|
+
export function resolveServerUrl(options, env, saved) {
|
|
11
|
+
const url = (options.serverUrl ?? env.KIOKU_SERVER_URL ?? saved?.url ?? '')
|
|
12
|
+
.trim()
|
|
13
|
+
.replace(/\/+$/, '')
|
|
14
|
+
if (!url) throw new UsageError('要给服务地址:--server-url https://kioku.example.com')
|
|
15
|
+
const problem = serverUrlProblem(url)
|
|
16
|
+
if (problem) throw new KiokuFailure(problem)
|
|
17
|
+
return url
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// platform:{ id, name },id 也是应用在 Kioku 里该有的运行时。返回 { url, key, saved }:
|
|
21
|
+
// saved 是上次写下的(没有为 null);预览时没给访问密钥、也没有上次的,key 为空字符串。
|
|
22
|
+
// io.login 是走浏览器授权的函数,只在终端里运行时有;io.beforeLogin 是走它之前平台要先做的检查
|
|
23
|
+
export async function resolveTarget(
|
|
24
|
+
{ id, name },
|
|
25
|
+
options,
|
|
26
|
+
{ env, out, readKey, plain, login, beforeLogin, readSaved },
|
|
27
|
+
) {
|
|
28
|
+
// 上次写下的:平台有自己放的地方时由它读(readSaved),否则读 kioku setup 写的那个文件
|
|
29
|
+
const saved = readSaved ? await readSaved() : await readProfile(id, env).catch(() => null)
|
|
30
|
+
const url = resolveServerUrl(options, env, saved)
|
|
31
|
+
// 已经有上次写下的访问密钥时,提示里直接回车是沿用它;没有时直接回车才是改用浏览器授权
|
|
32
|
+
const hasSaved = Boolean(saved?.key)
|
|
33
|
+
const canLogin = Boolean(login) && !hasSaved
|
|
34
|
+
// 预览时不提示输入:没在环境变量里给访问密钥就沿用上次的,都没有就不核对
|
|
35
|
+
const given =
|
|
36
|
+
options.dryRun && !env.KIOKU_API_KEY ? '' : await readKey({ env, canLogin, hasSaved })
|
|
37
|
+
let key = given || saved?.key || ''
|
|
38
|
+
// 什么都没给:在终端里的话改用浏览器授权。先让平台看一眼自己这边写不写得进去:
|
|
39
|
+
// 访问密钥只在签发时给一次,签了却写不下的话会留下一个没人拿着的访问密钥
|
|
40
|
+
if (!key && !options.dryRun && login) {
|
|
41
|
+
await beforeLogin?.()
|
|
42
|
+
key = await login({ url, id })
|
|
43
|
+
}
|
|
44
|
+
// 写文件、发请求之前先看格式:带着换行这类字符的访问密钥写进配置文件会让整份配置读不了
|
|
45
|
+
const keyProblem = key ? keyFormatError(key) : null
|
|
46
|
+
if (keyProblem) throw new KiokuFailure(keyProblem)
|
|
47
|
+
if (!key && !options.dryRun) {
|
|
48
|
+
throw new KiokuFailure('没有给访问密钥:设置 KIOKU_API_KEY,或者从标准输入给')
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
if (key && options.check) {
|
|
52
|
+
const who = await whoami({ url, key })
|
|
53
|
+
const family = who.app.runtimeFamily
|
|
54
|
+
out.write(`✓ 访问密钥可用:应用 ${plain(who.app.name)},运行时 ${plain(family)}\n`)
|
|
55
|
+
if (family !== id) {
|
|
56
|
+
out.write(
|
|
57
|
+
`! 这个应用的运行时不是 ${id},注入的内容不按 ${name} 的格式:在管理界面为 ${name} 另建一个应用\n`,
|
|
58
|
+
)
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return { url, key, saved }
|
|
62
|
+
}
|
package/lib/text.mjs
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// 不由本命令写的文字(服务端给的名字、环境变量里的地址)打印之前压成一行:控制字符、行与段落分隔符、
|
|
2
|
+
// 改变显示方向的格式字符都换成空格,免得伪造出一行结果;截断时不切开代理对
|
|
3
|
+
export function plain(value) {
|
|
4
|
+
const text = String(value ?? '')
|
|
5
|
+
.replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+/gu, ' ')
|
|
6
|
+
.trim()
|
|
7
|
+
return Array.from(text).slice(0, 200).join('')
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
// 地址只打印协议、主机与路径:写在地址里的账号密码、查询参数不打印
|
|
11
|
+
export function shownUrl(url) {
|
|
12
|
+
const { origin, pathname } = new URL(url)
|
|
13
|
+
return plain(origin + pathname.replace(/\/+$/, ''))
|
|
14
|
+
}
|
package/lib/usage.mjs
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,31 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kioku-memory/cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Kioku 的命令行:把凭据交给命令(kioku run)、停用各平台自带的长期记忆(kioku setup)、检查配置(kioku doctor)",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"homepage": "https://github.com/lonelyman0108/kioku-plugins/tree/main/packages/cli",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/lonelyman0108/kioku-plugins.git",
|
|
10
|
+
"directory": "packages/cli"
|
|
11
|
+
},
|
|
12
|
+
"keywords": [
|
|
13
|
+
"kioku",
|
|
14
|
+
"memory",
|
|
15
|
+
"agent"
|
|
16
|
+
],
|
|
17
|
+
"bin": {
|
|
18
|
+
"kioku": "bin/kioku"
|
|
19
|
+
},
|
|
20
|
+
"files": [
|
|
21
|
+
"bin",
|
|
22
|
+
"lib",
|
|
23
|
+
"NOTICE"
|
|
24
|
+
],
|
|
25
|
+
"engines": {
|
|
26
|
+
"node": ">=18"
|
|
27
|
+
},
|
|
28
|
+
"publishConfig": {
|
|
29
|
+
"access": "public"
|
|
30
|
+
}
|
|
31
|
+
}
|