@kioku-memory/cli 0.0.0 → 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/NOTICE +3 -0
- package/README.md +100 -3
- package/bin/kioku +11 -0
- package/lib/api.mjs +35 -0
- package/lib/codex.mjs +309 -0
- package/lib/command.mjs +135 -0
- package/lib/config.mjs +6 -4
- package/lib/doctor.mjs +32 -50
- package/lib/dsh.mjs +75 -0
- package/lib/files.mjs +92 -0
- package/lib/hermes.mjs +261 -0
- package/lib/import.mjs +262 -0
- package/lib/kioku.mjs +31 -4
- package/lib/lifecycle.mjs +29 -4
- 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 +59 -1
- package/lib/profile.mjs +100 -0
- package/lib/secret.mjs +86 -0
- package/lib/setup.mjs +50 -92
- package/lib/sources.mjs +333 -0
- package/lib/target.mjs +62 -0
- package/lib/text.mjs +14 -0
- package/package.json +1 -1
package/lib/doctor.mjs
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
// kioku doctor:检查地址与访问密钥能不能用、访问密钥的权限,以及平台这一边配好没有。
|
|
2
2
|
// 每项一行:✓ 正常,! 要留意,✗ 有问题;有 ✗ 时退出码为 1
|
|
3
3
|
|
|
4
|
-
import { loadConfig } from './config.mjs'
|
|
5
|
-
import {
|
|
4
|
+
import { loadConfig, NotConfigured } from './config.mjs'
|
|
5
|
+
import { whoami } from './api.mjs'
|
|
6
|
+
import { failureText, KiokuFailure } from './http.mjs'
|
|
6
7
|
import { detectPlatform, platformNames, PLATFORMS } from './platforms.mjs'
|
|
7
|
-
import { readSettings } from './
|
|
8
|
+
import { readSettings } from './files.mjs'
|
|
9
|
+
import { plain, shownUrl } from './text.mjs'
|
|
8
10
|
import { UsageError } from './usage.mjs'
|
|
9
11
|
|
|
10
12
|
export const DOCTOR_USAGE = `用法:kioku doctor [平台]
|
|
@@ -16,7 +18,6 @@ export const DOCTOR_USAGE = `用法:kioku doctor [平台]
|
|
|
16
18
|
有问题的项以 ✗ 开头,这时退出码为 1。
|
|
17
19
|
`
|
|
18
20
|
|
|
19
|
-
const TIMEOUT = 8000
|
|
20
21
|
// 与管理界面的用词一致
|
|
21
22
|
const LAYERS = {
|
|
22
23
|
core: '通用',
|
|
@@ -29,21 +30,6 @@ const LAYERS = {
|
|
|
29
30
|
const SENSITIVITIES = { public: '公开', internal: '内部', private: '私密', secret: '机密' }
|
|
30
31
|
const CAPABILITIES = { none: '不可用', use: '取用', manage: '管理' }
|
|
31
32
|
|
|
32
|
-
// 不由本命令写的文字(服务端给的名字、环境变量里的地址)打印之前压成一行:控制字符、行与段落分隔符、
|
|
33
|
-
// 改变显示方向的格式字符都换成空格,免得伪造出一行结果;截断时不切开代理对
|
|
34
|
-
function plain(value) {
|
|
35
|
-
const text = String(value ?? '')
|
|
36
|
-
.replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+/gu, ' ')
|
|
37
|
-
.trim()
|
|
38
|
-
return Array.from(text).slice(0, 200).join('')
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
// 地址只打印协议、主机与路径:写在地址里的账号密码、查询参数不打印
|
|
42
|
-
function shownUrl(url) {
|
|
43
|
-
const { origin, pathname } = new URL(url)
|
|
44
|
-
return plain(origin + pathname.replace(/\/+$/, ''))
|
|
45
|
-
}
|
|
46
|
-
|
|
47
33
|
function named(names, value) {
|
|
48
34
|
return Object.hasOwn(names, value) ? names[value] : plain(value)
|
|
49
35
|
}
|
|
@@ -53,35 +39,6 @@ function layersText(layers) {
|
|
|
53
39
|
return layers.map((layer) => named(LAYERS, layer)).join('、')
|
|
54
40
|
}
|
|
55
41
|
|
|
56
|
-
async function whoami({ url, key }) {
|
|
57
|
-
let res
|
|
58
|
-
let data
|
|
59
|
-
try {
|
|
60
|
-
res = await fetch(`${url}/v1/whoami`, {
|
|
61
|
-
headers: { authorization: `Bearer ${key}` },
|
|
62
|
-
// 不跟着跳转走:访问密钥只发给配置的地址
|
|
63
|
-
redirect: 'manual',
|
|
64
|
-
signal: AbortSignal.timeout(TIMEOUT),
|
|
65
|
-
})
|
|
66
|
-
data = await res.json().catch(() => null)
|
|
67
|
-
} catch (err) {
|
|
68
|
-
throw new KiokuFailure(fetchFailure(err, TIMEOUT))
|
|
69
|
-
}
|
|
70
|
-
if (isRedirect(res.status)) {
|
|
71
|
-
throw new KiokuFailure(redirectError(res.status, res.headers.get('location'), url))
|
|
72
|
-
}
|
|
73
|
-
if (res.status === 401) throw new KiokuFailure('访问密钥无效或已吊销')
|
|
74
|
-
if (!res.ok) throw new KiokuFailure(`Kioku 返回 HTTP ${res.status}`)
|
|
75
|
-
if (
|
|
76
|
-
typeof data?.app?.runtimeFamily !== 'string' ||
|
|
77
|
-
data.scopes === null ||
|
|
78
|
-
typeof data.scopes !== 'object'
|
|
79
|
-
) {
|
|
80
|
-
throw new KiokuFailure('Kioku 的响应格式不对')
|
|
81
|
-
}
|
|
82
|
-
return data
|
|
83
|
-
}
|
|
84
|
-
|
|
85
42
|
export function parseDoctorArgs(argv) {
|
|
86
43
|
const names = []
|
|
87
44
|
for (const arg of argv) {
|
|
@@ -111,8 +68,22 @@ export async function doctor(
|
|
|
111
68
|
|
|
112
69
|
let who = null
|
|
113
70
|
try {
|
|
114
|
-
|
|
115
|
-
|
|
71
|
+
// 平台把地址与访问密钥放在自己的文件里时先读它,没有再看环境变量
|
|
72
|
+
const profile = platform?.readConfig ? await platform.readConfig(env) : null
|
|
73
|
+
let config = profile
|
|
74
|
+
if (!config) {
|
|
75
|
+
try {
|
|
76
|
+
config = await loadConfig(env)
|
|
77
|
+
} catch (err) {
|
|
78
|
+
// 这个平台有自己放配置的地方、却什么都没配:说怎么配,不说别的平台的做法。
|
|
79
|
+
// 环境变量里配了但不对的(地址无效、访问密钥文件读不了)照原样报
|
|
80
|
+
if (platform?.readConfig && err instanceof NotConfigured) {
|
|
81
|
+
throw new KiokuFailure(`还没有给 ${platform.name} 配过:运行 kioku setup ${id}`)
|
|
82
|
+
}
|
|
83
|
+
throw err
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
ok(`地址 ${shownUrl(config.url)}${profile ? `(${profile.file})` : ''}`)
|
|
116
87
|
who = await whoami(config)
|
|
117
88
|
} catch (err) {
|
|
118
89
|
bad(failureText(err))
|
|
@@ -137,6 +108,17 @@ export async function doctor(
|
|
|
137
108
|
out.write(`没有认出平台,只查了地址与访问密钥;要查平台的配置,写上平台:${platformNames()}\n`)
|
|
138
109
|
return failed ? 1 : 0
|
|
139
110
|
}
|
|
111
|
+
if (platform.inspect) {
|
|
112
|
+
try {
|
|
113
|
+
await platform.inspect(
|
|
114
|
+
{ env, cwd },
|
|
115
|
+
{ ok, warn, bad, note: (text) => out.write(` ${text}\n`) },
|
|
116
|
+
)
|
|
117
|
+
} catch (err) {
|
|
118
|
+
bad(failureText(err))
|
|
119
|
+
}
|
|
120
|
+
return failed ? 1 : 0
|
|
121
|
+
}
|
|
140
122
|
let settings = null
|
|
141
123
|
try {
|
|
142
124
|
settings = (await readSettings(platform.settingsFile(env))).settings
|
package/lib/dsh.mjs
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// DeepSeek Harness 这个平台的 kioku setup 与 kioku doctor。
|
|
2
|
+
// 它没有自带的长期记忆要停用;插件与 MCP 客户端都由本仓库的补丁装上,读本机文件里的服务地址与访问密钥。
|
|
3
|
+
// 所以 setup 只做一件事:把服务地址与访问密钥写进本机的文件
|
|
4
|
+
|
|
5
|
+
import { readdir } from 'node:fs/promises'
|
|
6
|
+
import { homedir } from 'node:os'
|
|
7
|
+
import { join } from 'node:path'
|
|
8
|
+
|
|
9
|
+
import { readSettings } from './files.mjs'
|
|
10
|
+
import { profileFile, readProfile, removeProfile, writeProfile } from './profile.mjs'
|
|
11
|
+
import { plain } from './text.mjs'
|
|
12
|
+
import { resolveTarget } from './target.mjs'
|
|
13
|
+
|
|
14
|
+
const PACKAGE = 'kioku-plugins'
|
|
15
|
+
const SOURCE = 'github:lonelyman0108/kioku-plugins'
|
|
16
|
+
|
|
17
|
+
export function dshHome(env) {
|
|
18
|
+
return env.DSH_HOME || join(homedir(), '.dsh')
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// 装了本仓库这个包的 profile 的名字;没有 profile 目录时为空
|
|
22
|
+
async function installedProfiles(env) {
|
|
23
|
+
const root = join(dshHome(env), 'profiles')
|
|
24
|
+
const names = await readdir(root).catch(() => [])
|
|
25
|
+
const found = []
|
|
26
|
+
for (const name of names.sort()) {
|
|
27
|
+
const { settings } = await readSettings(join(root, name, 'package.json')).catch(() => ({}))
|
|
28
|
+
const bundles = settings?.dsh?.profile?.bundles
|
|
29
|
+
if (Array.isArray(bundles) && bundles.includes(PACKAGE)) found.push(name)
|
|
30
|
+
}
|
|
31
|
+
return found
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const installHint = `dsh plugin --profile <profile> add ${SOURCE}`
|
|
35
|
+
|
|
36
|
+
export async function setupDsh(options, io) {
|
|
37
|
+
const { env, out } = io
|
|
38
|
+
const profile = profileFile('dsh', env)
|
|
39
|
+
if (options.undo) {
|
|
40
|
+
if (options.dryRun) out.write(`${profile}:删掉\n没有写入(--dry-run)\n`)
|
|
41
|
+
else if (await removeProfile('dsh', env)) out.write(`已删掉 ${profile}\n`)
|
|
42
|
+
else out.write(`${profile} 本来就没有\n`)
|
|
43
|
+
out.write(`插件要另外卸载:dsh plugin --profile <profile> remove ${PACKAGE}\n`)
|
|
44
|
+
return 0
|
|
45
|
+
}
|
|
46
|
+
const { url, key, saved } = await resolveTarget(
|
|
47
|
+
{ id: 'dsh', name: 'DeepSeek Harness' },
|
|
48
|
+
options,
|
|
49
|
+
io,
|
|
50
|
+
)
|
|
51
|
+
const same = Boolean(saved && saved.url === url && saved.key === key)
|
|
52
|
+
if (same) out.write(`${profile} 不用改\n`)
|
|
53
|
+
else out.write(`${profile}:写入服务地址与访问密钥(只给本人读写)\n`)
|
|
54
|
+
if (options.dryRun) {
|
|
55
|
+
out.write('没有写入(--dry-run)\n')
|
|
56
|
+
return 0
|
|
57
|
+
}
|
|
58
|
+
if (!same) await writeProfile('dsh', { url, key }, env)
|
|
59
|
+
const profiles = await installedProfiles(env)
|
|
60
|
+
out.write('DeepSeek Harness 已配好,重启 dsh 后生效(读写记忆的工具在启动时连上)。\n')
|
|
61
|
+
if (profiles.length) out.write(`装了插件的 profile:${profiles.map(plain).join('、')}\n`)
|
|
62
|
+
else out.write(`接下来给要用的 profile 装上插件(web、tui 这些各装一次):${installHint}\n`)
|
|
63
|
+
return 0
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export async function inspectDsh({ env }, { ok, warn, note }) {
|
|
67
|
+
const profile = await readProfile('dsh', env).catch(() => null)
|
|
68
|
+
if (!profile)
|
|
69
|
+
warn('没有 kioku setup dsh 写下的地址与访问密钥,插件不会生效:运行 kioku setup dsh')
|
|
70
|
+
const profiles = await installedProfiles(env)
|
|
71
|
+
if (profiles.length) ok(`装了 kioku 插件的 profile:${profiles.map(plain).join('、')}`)
|
|
72
|
+
else warn(`没有哪个 profile 装了 kioku 的插件:${installHint}`)
|
|
73
|
+
note('插件按 profile 装:没装的 profile 里没有长期记忆')
|
|
74
|
+
ok('DeepSeek Harness 没有自带的长期记忆要停用')
|
|
75
|
+
}
|
package/lib/files.mjs
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// kioku setup 读写平台设置文件的共用部分。设置文件是用户的,里面还有别的工具写的内容,平台自己也随时在改它,
|
|
2
|
+
// 所以:读不懂的不动它,符号链接改它指向的文件,先写临时文件,改名之前确认没有别人刚改过,备份只留第一份
|
|
3
|
+
|
|
4
|
+
import { randomUUID } from 'node:crypto'
|
|
5
|
+
import { constants } from 'node:fs'
|
|
6
|
+
import { copyFile, mkdir, readFile, realpath, rename, rm, stat, writeFile } from 'node:fs/promises'
|
|
7
|
+
import { dirname } from 'node:path'
|
|
8
|
+
|
|
9
|
+
import { errorKind, KiokuFailure } from './http.mjs'
|
|
10
|
+
|
|
11
|
+
// 读文件的原文;没有这个文件时为 null
|
|
12
|
+
export async function readText(file) {
|
|
13
|
+
try {
|
|
14
|
+
return await readFile(file, 'utf8')
|
|
15
|
+
} catch (err) {
|
|
16
|
+
if (err?.code === 'ENOENT') return null
|
|
17
|
+
throw new KiokuFailure(`无法读取 ${file}(${errorKind(err)})`)
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// 读 JSON 的设置文件:没有这个文件、或者文件是空的,按空的设置;内容不是 JSON 对象时不动它,报错。
|
|
22
|
+
// text 是读到的原文,没有这个文件时为 null
|
|
23
|
+
export async function readSettings(file) {
|
|
24
|
+
const text = await readText(file)
|
|
25
|
+
if (text === null) return { settings: {}, text: null }
|
|
26
|
+
// 开头的 BOM 不算内容
|
|
27
|
+
const body = text.replace(/^\uFEFF/, '')
|
|
28
|
+
if (!body.trim()) return { settings: {}, text }
|
|
29
|
+
let settings
|
|
30
|
+
try {
|
|
31
|
+
settings = JSON.parse(body)
|
|
32
|
+
} catch {
|
|
33
|
+
settings = null
|
|
34
|
+
}
|
|
35
|
+
if (settings === null || typeof settings !== 'object' || Array.isArray(settings)) {
|
|
36
|
+
throw new KiokuFailure(`${file} 不是 JSON 对象,没有改动它`)
|
|
37
|
+
}
|
|
38
|
+
return { settings, text }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// 沿用原文件的缩进(取第一处,没有就用两个空格)、换行符和结尾有没有换行;别的排版按 JSON 的默认写法
|
|
42
|
+
export function serialize(settings, text) {
|
|
43
|
+
const indent = /\n([ \t]+)"/.exec(text ?? '')?.[1] ?? ' '
|
|
44
|
+
const eol = text?.includes('\r\n') ? '\r\n' : '\n'
|
|
45
|
+
const tail = text === null || !text.trim() || /\n$/.test(text) ? eol : ''
|
|
46
|
+
return JSON.stringify(settings, null, indent).replaceAll('\n', eol) + tail
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// 把 body 写成设置文件的新内容,返回这次有没有留备份。text 是开始时读到的原文,没有这个文件时为 null。
|
|
50
|
+
// - 设置文件是符号链接时改它指向的文件,不把链接换成普通文件。
|
|
51
|
+
// - 先写临时文件再改名:写到一半被打断时原来的设置还在;失败时临时文件删掉。
|
|
52
|
+
// - 改名之前再读一次,和开始时读到的不一样就不写:别的程序刚改过,写下去会盖掉它的改动。
|
|
53
|
+
// - 备份只留第一份:之后再改时不覆盖,最早的原文件才留得住。原文里有不该多留一份的内容时(backup 为假)不备份。
|
|
54
|
+
// 权限沿用原文件的,新建的只给本人
|
|
55
|
+
export async function safeWrite(file, body, text, { backup = true } = {}) {
|
|
56
|
+
let target = file
|
|
57
|
+
let temp
|
|
58
|
+
try {
|
|
59
|
+
if (text === null) await mkdir(dirname(file), { recursive: true })
|
|
60
|
+
else target = await realpath(file)
|
|
61
|
+
const mode = text === null ? 0o600 : (await stat(target)).mode & 0o777
|
|
62
|
+
temp = `${target}.${randomUUID()}.tmp`
|
|
63
|
+
await writeFile(temp, body, { mode, flag: 'wx' })
|
|
64
|
+
const current = await readFile(target, 'utf8').catch((err) => {
|
|
65
|
+
if (err?.code === 'ENOENT') return null
|
|
66
|
+
throw err
|
|
67
|
+
})
|
|
68
|
+
if (current !== text) {
|
|
69
|
+
throw new KiokuFailure(`${file} 刚被别的程序改过,没有写入:重新运行一次`)
|
|
70
|
+
}
|
|
71
|
+
let backedUp = false
|
|
72
|
+
if (text !== null && backup) {
|
|
73
|
+
try {
|
|
74
|
+
await copyFile(target, `${file}.kioku-backup`, constants.COPYFILE_EXCL)
|
|
75
|
+
backedUp = true
|
|
76
|
+
} catch (err) {
|
|
77
|
+
if (err?.code !== 'EEXIST') throw err
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
await rename(temp, target)
|
|
81
|
+
return backedUp
|
|
82
|
+
} catch (err) {
|
|
83
|
+
if (temp) await rm(temp, { force: true }).catch(() => {})
|
|
84
|
+
if (err instanceof KiokuFailure) throw err
|
|
85
|
+
throw new KiokuFailure(`无法写入 ${file}(${errorKind(err)})`)
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// 写回 JSON 的设置文件
|
|
90
|
+
export function writeSettings(file, settings, text) {
|
|
91
|
+
return safeWrite(file, serialize(settings, text), text)
|
|
92
|
+
}
|
package/lib/hermes.mjs
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
// Hermes 这个平台的 kioku setup 与 kioku doctor。
|
|
2
|
+
// Hermes 的记忆 provider 从这个 profile 的 .env 读 KIOKU_SERVER_URL 与 KIOKU_API_KEY,所以地址与访问密钥写在那里
|
|
3
|
+
// (不另放一份);选 provider、关掉内置的两份记忆文件是 config.yaml 里的三项,交给 Hermes 自己的 hermes config set 去改,
|
|
4
|
+
// 不自己动它的 YAML
|
|
5
|
+
|
|
6
|
+
import { stat } from 'node:fs/promises'
|
|
7
|
+
import { homedir } from 'node:os'
|
|
8
|
+
import { join } from 'node:path'
|
|
9
|
+
|
|
10
|
+
import { capture } from './command.mjs'
|
|
11
|
+
import { readText, safeWrite } from './files.mjs'
|
|
12
|
+
import { keyFormatError, KiokuFailure } from './http.mjs'
|
|
13
|
+
import { serverUrlProblem } from './profile.mjs'
|
|
14
|
+
import { resolveTarget } from './target.mjs'
|
|
15
|
+
|
|
16
|
+
const SOURCE = 'lonelyman0108/kioku-plugins/plugins/hermes'
|
|
17
|
+
// 要 Hermes 改的三项:选 Kioku,关掉内置的 MEMORY.md 与 USER.md(不关的话两边各记一份)
|
|
18
|
+
const SETTINGS = [
|
|
19
|
+
['memory.provider', 'kioku'],
|
|
20
|
+
['memory.memory_enabled', 'false'],
|
|
21
|
+
['memory.user_profile_enabled', 'false'],
|
|
22
|
+
]
|
|
23
|
+
const RESTORED = [
|
|
24
|
+
['memory.provider', ''],
|
|
25
|
+
['memory.memory_enabled', 'true'],
|
|
26
|
+
['memory.user_profile_enabled', 'true'],
|
|
27
|
+
]
|
|
28
|
+
const URL_KEY = 'KIOKU_SERVER_URL'
|
|
29
|
+
const API_KEY = 'KIOKU_API_KEY'
|
|
30
|
+
|
|
31
|
+
export function hermesHome(env) {
|
|
32
|
+
return env.HERMES_HOME || join(homedir(), '.hermes')
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// .env 里的一行「名字=值」。值两边成对的引号去掉;没加引号的值后面的「 # 注释」不算值。不是这种行时为 null
|
|
36
|
+
function envLine(line) {
|
|
37
|
+
const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/.exec(line)
|
|
38
|
+
if (!match) return null
|
|
39
|
+
const quoted = /^(["'])(.*)\1(?:\s+#.*)?$/.exec(match[2])
|
|
40
|
+
const value = quoted ? quoted[2] : match[2].replace(/\s+#.*$/, '')
|
|
41
|
+
return { name: match[1], value }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// .env 里现在写的地址与访问密钥(同名的写了几行时以最后一行为准,和 Hermes 读它的方式一致);
|
|
45
|
+
// 没有、不完整、格式不对时为 null
|
|
46
|
+
export async function readHermesConfig(env) {
|
|
47
|
+
const file = join(hermesHome(env), '.env')
|
|
48
|
+
const text = await readText(file)
|
|
49
|
+
const values = {}
|
|
50
|
+
for (const line of (text ?? '').split(/\r?\n/)) {
|
|
51
|
+
const pair = envLine(line)
|
|
52
|
+
if (pair) values[pair.name] = pair.value
|
|
53
|
+
}
|
|
54
|
+
const url = (values[URL_KEY] ?? '').trim().replace(/\/+$/, '')
|
|
55
|
+
const key = (values[API_KEY] ?? '').trim()
|
|
56
|
+
if (!url || !key || serverUrlProblem(url) || keyFormatError(key)) return null
|
|
57
|
+
return { url, key, file }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// 把这几项写进 .env 的全文:同名的行只留一处(换成新值),没有的加在最后;values 里为 null 的全都去掉。
|
|
61
|
+
// 别的行不动;没有要改的时候原样返回,不顺手整理空行与换行符
|
|
62
|
+
function withEnv(text, values) {
|
|
63
|
+
const eol = text?.includes('\r\n') ? '\r\n' : '\n'
|
|
64
|
+
const written = new Set()
|
|
65
|
+
let touched = false
|
|
66
|
+
const lines = []
|
|
67
|
+
for (const line of text ? text.split(/\r?\n/) : []) {
|
|
68
|
+
const pair = envLine(line)
|
|
69
|
+
if (!pair || !Object.hasOwn(values, pair.name)) {
|
|
70
|
+
lines.push(line)
|
|
71
|
+
continue
|
|
72
|
+
}
|
|
73
|
+
const wanted = values[pair.name]
|
|
74
|
+
// 同名的第二行起、要去掉的:都不留(留着的话 Hermes 读到的是最后那一行的旧值)
|
|
75
|
+
if (wanted === null || written.has(pair.name)) {
|
|
76
|
+
touched = true
|
|
77
|
+
continue
|
|
78
|
+
}
|
|
79
|
+
written.add(pair.name)
|
|
80
|
+
const next = `${pair.name}=${wanted}`
|
|
81
|
+
if (next !== line) touched = true
|
|
82
|
+
lines.push(next)
|
|
83
|
+
}
|
|
84
|
+
const missing = Object.entries(values).filter(
|
|
85
|
+
([name, value]) => value !== null && !written.has(name),
|
|
86
|
+
)
|
|
87
|
+
if (!touched && !missing.length) return text ?? ''
|
|
88
|
+
while (lines.length && lines.at(-1) === '') lines.pop()
|
|
89
|
+
for (const [name, value] of missing) lines.push(`${name}=${value}`)
|
|
90
|
+
return lines.length ? `${lines.join(eol)}${eol}` : ''
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// 调 hermes 命令。找不到这个命令时返回 null;失败(含超时)时抛 KiokuFailure(不带输出:里面可能有别的配置)
|
|
94
|
+
async function hermes(env, args) {
|
|
95
|
+
const result = await capture(env.KIOKU_HERMES_BIN || 'hermes', args, env, { timeout: 30_000 })
|
|
96
|
+
if (!result.found) return null
|
|
97
|
+
if (!result.ok) throw new KiokuFailure(`hermes ${args.slice(0, 3).join(' ')} 没有成功`)
|
|
98
|
+
return result.stdout
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// 读 Hermes 的一项配置:null 是没有 hermes 命令,undefined 是没读出来(命令失败),否则是值(没设时是空字符串)
|
|
102
|
+
async function configValue(env, key) {
|
|
103
|
+
let out
|
|
104
|
+
try {
|
|
105
|
+
out = await hermes(env, ['config', 'get', key])
|
|
106
|
+
} catch {
|
|
107
|
+
return undefined
|
|
108
|
+
}
|
|
109
|
+
if (out === null) return null
|
|
110
|
+
return out.trim().split(/\r?\n/).at(-1)?.trim() ?? ''
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const sameValue = (a, b) => String(a).toLowerCase() === String(b).toLowerCase()
|
|
114
|
+
|
|
115
|
+
// 逐项让 Hermes 改配置,改完读回来核对(托管的安装里 config set 不生效却照样成功退出)。
|
|
116
|
+
// 返回 'done'、'no-hermes'(没有这个命令)或 'failed'(命令失败或没改成)。不抛错:
|
|
117
|
+
// 调用方这时多半已经把访问密钥写下了,不能让这里的失败看起来像什么都没写
|
|
118
|
+
async function applySettings(env, settings) {
|
|
119
|
+
try {
|
|
120
|
+
for (const [key, value] of settings) {
|
|
121
|
+
if ((await hermes(env, ['config', 'set', key, value])) === null) return 'no-hermes'
|
|
122
|
+
}
|
|
123
|
+
for (const [key, value] of settings) {
|
|
124
|
+
const now = await configValue(env, key)
|
|
125
|
+
if (now === null || now === undefined || !sameValue(now, value)) return 'failed'
|
|
126
|
+
}
|
|
127
|
+
return 'done'
|
|
128
|
+
} catch {
|
|
129
|
+
return 'failed'
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function manual(out, settings, state) {
|
|
134
|
+
out.write(
|
|
135
|
+
state === 'no-hermes'
|
|
136
|
+
? '没有找到 hermes 命令,这几项要自己运行:\n'
|
|
137
|
+
: 'Hermes 的配置没有改成(它的命令失败了,或者这份安装的配置是托管的),这几项要自己处理:\n',
|
|
138
|
+
)
|
|
139
|
+
for (const [key, value] of settings) out.write(` hermes config set ${key} ${value || '""'}\n`)
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async function installed(env) {
|
|
143
|
+
return Boolean(
|
|
144
|
+
await stat(join(hermesHome(env), 'plugins', 'kioku', 'plugin.yaml')).catch(() => null),
|
|
145
|
+
)
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async function undo({ dryRun }, { env, out }) {
|
|
149
|
+
const file = join(hermesHome(env), '.env')
|
|
150
|
+
const text = await readText(file)
|
|
151
|
+
const next = withEnv(text, { [URL_KEY]: null, [API_KEY]: null })
|
|
152
|
+
const changed = text !== null && next !== text
|
|
153
|
+
if (changed) out.write(`${file}\n ${URL_KEY}、${API_KEY}:去掉\n`)
|
|
154
|
+
// 只在现在选的还是 kioku 时把配置改回去:之后换成了别的 provider 的话,不去动它
|
|
155
|
+
const provider = await configValue(env, 'memory.provider')
|
|
156
|
+
const ours = provider === 'kioku'
|
|
157
|
+
if (ours) {
|
|
158
|
+
out.write('Hermes 的配置\n')
|
|
159
|
+
for (const [key, value] of RESTORED) out.write(` ${key} → ${value || '(内置的)'}\n`)
|
|
160
|
+
} else if (provider === null) {
|
|
161
|
+
out.write('没有找到 hermes 命令,Hermes 的配置没有动\n')
|
|
162
|
+
} else {
|
|
163
|
+
out.write('Hermes 现在选的记忆 provider 不是 kioku,它的配置没有动\n')
|
|
164
|
+
}
|
|
165
|
+
if (dryRun) {
|
|
166
|
+
out.write('没有写入(--dry-run)\n')
|
|
167
|
+
return 0
|
|
168
|
+
}
|
|
169
|
+
// .env 里有访问密钥与别的密钥,不留备份
|
|
170
|
+
if (changed) await safeWrite(file, next, text, { backup: false })
|
|
171
|
+
if (ours) {
|
|
172
|
+
const state = await applySettings(env, RESTORED)
|
|
173
|
+
if (state !== 'done') manual(out, RESTORED, state)
|
|
174
|
+
else out.write('Hermes 改回用内置的记忆(两个开关都打开了;之前自己关过的要再关一次)。\n')
|
|
175
|
+
}
|
|
176
|
+
out.write('provider 要另外卸载:hermes plugins remove kioku\n')
|
|
177
|
+
return 0
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// kioku login 申请之前、setup 动手之前先看:Hermes 的目录在不在
|
|
181
|
+
export async function preflightHermes({ env }) {
|
|
182
|
+
const home = hermesHome(env)
|
|
183
|
+
if (!(await stat(home).catch(() => null))?.isDirectory()) {
|
|
184
|
+
throw new KiokuFailure(
|
|
185
|
+
`没有找到 Hermes 的目录 ${home}:先装好并运行一次 Hermes,或者用 HERMES_HOME 指明`,
|
|
186
|
+
)
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
export async function setupHermes(options, io) {
|
|
191
|
+
const { env, out } = io
|
|
192
|
+
if (options.undo) return undo(options, io)
|
|
193
|
+
const home = hermesHome(env)
|
|
194
|
+
await preflightHermes({ env })
|
|
195
|
+
const { url, key, saved } = await resolveTarget({ id: 'hermes', name: 'Hermes' }, options, {
|
|
196
|
+
...io,
|
|
197
|
+
readSaved: () => readHermesConfig(env),
|
|
198
|
+
})
|
|
199
|
+
const file = join(home, '.env')
|
|
200
|
+
const text = await readText(file)
|
|
201
|
+
const next = withEnv(text, { [URL_KEY]: url, [API_KEY]: key })
|
|
202
|
+
// 同名的行写了几处时,哪怕最后生效的值是对的也要收拾成一处
|
|
203
|
+
const same = Boolean(saved && saved.url === url && saved.key === key) && next === (text ?? '')
|
|
204
|
+
if (same) out.write(`${file} 不用改\n`)
|
|
205
|
+
else out.write(`${file}\n ${URL_KEY}、${API_KEY}:写入\n`)
|
|
206
|
+
out.write('Hermes 的配置\n')
|
|
207
|
+
for (const [name, value] of SETTINGS) out.write(` ${name} → ${value}\n`)
|
|
208
|
+
if (options.dryRun) {
|
|
209
|
+
out.write('没有写入(--dry-run)\n')
|
|
210
|
+
return 0
|
|
211
|
+
}
|
|
212
|
+
// .env 里有访问密钥与别的密钥,不留备份;新建的只给本人读写(safeWrite 的规矩)
|
|
213
|
+
if (!same) await safeWrite(file, next, text, { backup: false })
|
|
214
|
+
// 访问密钥这时已经写下了:后面改 Hermes 的配置不成也不算失败,把要做的列出来
|
|
215
|
+
const state = await applySettings(env, SETTINGS)
|
|
216
|
+
if (state === 'done') {
|
|
217
|
+
out.write('Hermes 已配好,新开会话生效。内置的 MEMORY.md、USER.md 不再读写,文件还在。\n')
|
|
218
|
+
} else {
|
|
219
|
+
out.write('地址与访问密钥已经写下。\n')
|
|
220
|
+
manual(out, SETTINGS, state)
|
|
221
|
+
}
|
|
222
|
+
if (!(await installed(env))) {
|
|
223
|
+
out.write(`接下来装上 provider:hermes plugins install ${SOURCE} --enable\n`)
|
|
224
|
+
}
|
|
225
|
+
return 0
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
export async function inspectHermes({ env }, { ok, warn, note }) {
|
|
229
|
+
const home = hermesHome(env)
|
|
230
|
+
if (!(await readHermesConfig(env))) {
|
|
231
|
+
warn(
|
|
232
|
+
`${join(home, '.env')} 里没有 Kioku 的地址与访问密钥,provider 不会生效:运行 kioku setup hermes`,
|
|
233
|
+
)
|
|
234
|
+
}
|
|
235
|
+
if (await installed(env)) ok('Hermes 里装了 kioku 的记忆 provider')
|
|
236
|
+
else warn(`Hermes 里没有装 kioku 的记忆 provider:hermes plugins install ${SOURCE} --enable`)
|
|
237
|
+
|
|
238
|
+
const provider = await configValue(env, 'memory.provider')
|
|
239
|
+
if (provider === null) {
|
|
240
|
+
note('没有找到 hermes 命令,查不了它的配置:用 hermes memory status 看')
|
|
241
|
+
return
|
|
242
|
+
}
|
|
243
|
+
const flags = [
|
|
244
|
+
[await configValue(env, 'memory.memory_enabled'), 'MEMORY.md'],
|
|
245
|
+
[await configValue(env, 'memory.user_profile_enabled'), 'USER.md'],
|
|
246
|
+
]
|
|
247
|
+
// 没读出来的不下结论
|
|
248
|
+
if (provider === undefined || flags.some(([value]) => value === undefined)) {
|
|
249
|
+
warn('Hermes 的配置没有读出来(hermes config get 失败了):用 hermes memory status 看')
|
|
250
|
+
return
|
|
251
|
+
}
|
|
252
|
+
if (provider === 'kioku') ok('Hermes 选的记忆 provider 是 kioku')
|
|
253
|
+
else warn(`Hermes 现在选的记忆 provider 不是 kioku:运行 kioku setup hermes`)
|
|
254
|
+
const builtin = flags.filter(([value]) => /^true$/i.test(value)).map(([, label]) => label)
|
|
255
|
+
if (builtin.length) {
|
|
256
|
+
warn(
|
|
257
|
+
`Hermes 内置的 ${builtin.join('、')} 还开着,会和 Kioku 各记一份:运行 kioku setup hermes 关掉`,
|
|
258
|
+
)
|
|
259
|
+
} else ok('Hermes 内置的记忆文件已停用')
|
|
260
|
+
note('只在本机的会话里生效;消息网关来的会话里不注入、不上报、不给工具')
|
|
261
|
+
}
|