@kioku-memory/cli 0.4.1 → 0.6.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/README.md +55 -43
- package/assets/plugins/agy/README.md +1 -1
- package/assets/plugins/agy/hooks/forward.mjs +48 -20
- package/assets/plugins/agy/lib/command.mjs +7 -1
- package/assets/plugins/agy/lib/config.mjs +3 -9
- package/assets/plugins/agy/lib/http.mjs +45 -0
- package/assets/plugins/agy/lib/kioku.mjs +6 -1
- package/assets/plugins/agy/lib/lifecycle.mjs +40 -5
- package/assets/plugins/agy/lib/mcp.mjs +40 -11
- package/assets/plugins/agy/lib/profile.mjs +1 -1
- package/assets/plugins/agy/lib/run.mjs +65 -31
- package/assets/plugins/gemini/README.md +1 -1
- package/assets/plugins/gemini/hooks/forward.mjs +30 -14
- package/assets/plugins/gemini/lib/command.mjs +7 -1
- package/assets/plugins/gemini/lib/config.mjs +3 -9
- package/assets/plugins/gemini/lib/http.mjs +45 -0
- package/assets/plugins/gemini/lib/kioku.mjs +6 -1
- package/assets/plugins/gemini/lib/lifecycle.mjs +40 -5
- package/assets/plugins/gemini/lib/mcp.mjs +40 -11
- package/assets/plugins/gemini/lib/profile.mjs +1 -1
- package/assets/plugins/gemini/lib/run.mjs +65 -31
- package/dist/index.mjs +9333 -4769
- package/package.json +1 -1
|
@@ -5,21 +5,42 @@ import { randomUUID } from 'node:crypto'
|
|
|
5
5
|
import { readFileSync } from 'node:fs'
|
|
6
6
|
import { chmod, mkdir, rename, rm, writeFile } from 'node:fs/promises'
|
|
7
7
|
|
|
8
|
-
import {
|
|
8
|
+
import {
|
|
9
|
+
fetchFailure,
|
|
10
|
+
isRedirect,
|
|
11
|
+
jsonOrNull,
|
|
12
|
+
KiokuFailure,
|
|
13
|
+
redirectError,
|
|
14
|
+
rejectionOf,
|
|
15
|
+
} from './http.mjs'
|
|
9
16
|
import { profileDir, profileFile } from './profile.mjs'
|
|
10
17
|
import { plain } from './text.mjs'
|
|
11
18
|
|
|
12
19
|
export const TOOLS_TIMEOUT = 8000
|
|
13
20
|
export const TOOL_CALL_TIMEOUT = 30_000
|
|
14
21
|
|
|
15
|
-
//
|
|
22
|
+
// 回答可能是一段事件流:合并同一事件里的多行 data,取最后一条非空载荷
|
|
16
23
|
function payloadOf(text, contentType) {
|
|
17
24
|
if (!contentType.includes('text/event-stream')) return text
|
|
18
|
-
const
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
25
|
+
const events = []
|
|
26
|
+
let current = []
|
|
27
|
+
for (const rawLine of text.split(/\r?\n/)) {
|
|
28
|
+
if (rawLine === '') {
|
|
29
|
+
if (current.length) {
|
|
30
|
+
events.push(current.join('\n'))
|
|
31
|
+
current = []
|
|
32
|
+
}
|
|
33
|
+
continue
|
|
34
|
+
}
|
|
35
|
+
if (rawLine.startsWith('data:')) current.push(rawLine.slice(5).trimStart())
|
|
36
|
+
}
|
|
37
|
+
if (current.length) events.push(current.join('\n'))
|
|
38
|
+
return (
|
|
39
|
+
events
|
|
40
|
+
.map((chunk) => chunk.trim())
|
|
41
|
+
.filter((chunk) => chunk && chunk !== '[DONE]')
|
|
42
|
+
.at(-1) ?? ''
|
|
43
|
+
)
|
|
23
44
|
}
|
|
24
45
|
|
|
25
46
|
// 一次 JSON-RPC 调用,返回 result。连不上、超时、取消、跳转、访问密钥无效、响应不对、服务端报错都以 KiokuFailure 抛出
|
|
@@ -49,7 +70,9 @@ export async function mcpCall({ url, key }, method, params, timeout, signal) {
|
|
|
49
70
|
if (isRedirect(res.status)) {
|
|
50
71
|
throw new KiokuFailure(redirectError(res.status, res.headers.get('location'), url))
|
|
51
72
|
}
|
|
52
|
-
|
|
73
|
+
// 401 与数据库不可用的 503 带着错误码,优先用这边的清晰提示
|
|
74
|
+
const rejected = res.ok ? null : rejectionOf(res.status, jsonOrNull(text))
|
|
75
|
+
if (rejected) throw rejected
|
|
53
76
|
if (!res.ok) throw new KiokuFailure(`Kioku 返回 HTTP ${res.status}`)
|
|
54
77
|
let data
|
|
55
78
|
try {
|
|
@@ -115,19 +138,25 @@ export function readToolCacheSync(platform, env) {
|
|
|
115
138
|
const data = JSON.parse(readFileSync(toolCacheFile(platform, env), 'utf8'))
|
|
116
139
|
if (typeof data?.url !== 'string') return null
|
|
117
140
|
const at = Number.isFinite(data.at) && data.at > 0 ? data.at : 0
|
|
118
|
-
|
|
141
|
+
const keyHash = typeof data.keyHash === 'string' && data.keyHash ? data.keyHash : undefined
|
|
142
|
+
return { url: data.url, ...(keyHash ? { keyHash } : {}), at, tools: toolsOf(data) }
|
|
119
143
|
} catch {
|
|
120
144
|
return null
|
|
121
145
|
}
|
|
122
146
|
}
|
|
123
147
|
|
|
124
148
|
// 写不进去不算失败:下次再取
|
|
125
|
-
export async function writeToolCache(
|
|
149
|
+
export async function writeToolCache(
|
|
150
|
+
platform,
|
|
151
|
+
{ url, keyHash = undefined, tools, at = Date.now() },
|
|
152
|
+
env,
|
|
153
|
+
) {
|
|
126
154
|
const file = toolCacheFile(platform, env)
|
|
127
155
|
const temp = `${file}.${randomUUID()}.tmp`
|
|
128
156
|
try {
|
|
129
157
|
await mkdir(profileDir(env), { recursive: true, mode: 0o700 })
|
|
130
|
-
|
|
158
|
+
const body = { url, ...(keyHash ? { keyHash } : {}), at, tools }
|
|
159
|
+
await writeFile(temp, `${JSON.stringify(body)}\n`, { mode: 0o600, flag: 'wx' })
|
|
131
160
|
await chmod(temp, 0o600)
|
|
132
161
|
await rename(temp, file)
|
|
133
162
|
return true
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// 没有自己的密钥存储的平台(Codex、pi 这类),地址与访问密钥放在本机的一个文件里:
|
|
2
2
|
// <配置目录>/kioku/<平台>.json,只给本人读写。kioku setup 写它,各平台的钩子与 kioku doctor 读它。
|
|
3
|
-
// 一个平台一个文件:每个平台在 Kioku
|
|
3
|
+
// 一个平台一个文件:每个平台在 Kioku 里使用各自的访问密钥,不共用
|
|
4
4
|
|
|
5
5
|
import { randomUUID } from 'node:crypto'
|
|
6
6
|
import { chmod, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
|
|
@@ -10,14 +10,18 @@ import { isatty } from 'node:tty'
|
|
|
10
10
|
import { killTree, launch } from './command.mjs'
|
|
11
11
|
import { loadConfig } from './config.mjs'
|
|
12
12
|
import {
|
|
13
|
+
DatabaseUnavailable,
|
|
13
14
|
errorKind,
|
|
14
15
|
failureText,
|
|
15
16
|
fetchFailure,
|
|
16
17
|
isRedirect,
|
|
18
|
+
KeyRejected,
|
|
17
19
|
KiokuFailure,
|
|
18
20
|
redirectError,
|
|
21
|
+
rejectionOf,
|
|
19
22
|
} from './http.mjs'
|
|
20
23
|
import { createRedactor, MIN_REDACT_CHARS, redactable } from './redact.mjs'
|
|
24
|
+
import { plain } from './text.mjs'
|
|
21
25
|
import { UsageError } from './usage.mjs'
|
|
22
26
|
|
|
23
27
|
// 等 Kioku 取值的上限(毫秒)
|
|
@@ -26,7 +30,8 @@ const TIMEOUT = 15_000
|
|
|
26
30
|
const MAX_REFS = 32
|
|
27
31
|
const MAX_PURPOSE = 200
|
|
28
32
|
const VARIABLE = /^[A-Za-z_][A-Za-z0-9_]*$/
|
|
29
|
-
const
|
|
33
|
+
const SLUG = /^[a-z0-9][a-z0-9._-]{0,63}$/
|
|
34
|
+
const FIELD = /^[a-z0-9][a-z0-9_-]{0,63}$/
|
|
30
35
|
const CONTROL = /\p{Cc}/u
|
|
31
36
|
// 不给命令留这两个变量,免得它把访问密钥或文件的位置顺手打印出来。这不是隔离:
|
|
32
37
|
// 访问密钥文件和命令属于同一个用户,命令照样读得到
|
|
@@ -56,21 +61,21 @@ const NOT_RERAISED = new Set([
|
|
|
56
61
|
'SIGXFSZ',
|
|
57
62
|
])
|
|
58
63
|
|
|
59
|
-
export const USAGE = `用法:kioku run -e
|
|
64
|
+
export const USAGE = `用法:kioku run -e 变量=<标识>[#<字段>] [-e …] [--purpose <用途>] -- <命令> [参数…]
|
|
60
65
|
|
|
61
66
|
向 Kioku 取凭据的值,放进环境变量交给命令;命令行和对话记录里只有变量名。
|
|
62
67
|
命令输出里原样出现的值换成 ***(少于 ${MIN_REDACT_CHARS} 个字符的值除外)。
|
|
63
68
|
打码只防值顺手出现在输出里,不是安全边界。
|
|
64
69
|
|
|
65
|
-
-e
|
|
66
|
-
--purpose <用途>
|
|
67
|
-
-h, --help
|
|
70
|
+
-e 变量=<标识>[#<字段>] 凭据 <标识>(或指定 <字段>)放进这个环境变量,可以写多个
|
|
71
|
+
--purpose <用途> 这次取用的用途,记进访问记录,最多 ${MAX_PURPOSE} 个字;用途里有空格时要加引号
|
|
72
|
+
-h, --help 显示本说明
|
|
68
73
|
|
|
69
74
|
命令不经过 shell 直接执行。参数里写的 $变量 会被外层的 shell 提前展开成空值;
|
|
70
75
|
要在参数里用变量,或者要用管道、重定向时,写成 sh -c '…',整段用单引号,变量放在双引号里:
|
|
71
76
|
|
|
72
|
-
kioku run -e PGPASSWORD=pg-main
|
|
73
|
-
kioku run -e TOKEN=github
|
|
77
|
+
kioku run -e PGPASSWORD=pg-main-password -- psql -h db.example.com -U app
|
|
78
|
+
kioku run -e TOKEN=github-token --purpose '查看 issue' -- sh -c 'curl -H "Authorization: Bearer $TOKEN" https://api.example.com/issues'
|
|
74
79
|
|
|
75
80
|
退出码与命令相同,命令被信号结束时 kioku 也以同一个信号结束;参数不对、取值失败时为 2。
|
|
76
81
|
地址与访问密钥:Claude Code 插件在会话开始时配好;在别处用时设置 KIOKU_SERVER_URL 与 KIOKU_API_KEY。
|
|
@@ -78,7 +83,7 @@ export const USAGE = `用法:kioku run -e 变量=<标识>#<字段> [-e …] [-
|
|
|
78
83
|
|
|
79
84
|
export { UsageError }
|
|
80
85
|
|
|
81
|
-
// 解析 kioku run 的参数。要看说明时返回 { help: true };否则返回 refs
|
|
86
|
+
// 解析 kioku run 的参数。要看说明时返回 { help: true };否则返回 refs(要取的标识与可选字段,同一项只取一次)、
|
|
82
87
|
// variables([变量名, 值在 refs 里的下标])、purpose、command 与 args
|
|
83
88
|
export function parseRunArgs(argv) {
|
|
84
89
|
const refs = []
|
|
@@ -91,13 +96,13 @@ export function parseRunArgs(argv) {
|
|
|
91
96
|
const arg = argv[i]
|
|
92
97
|
if (arg === '-h' || arg === '--help') return { help: true }
|
|
93
98
|
if (arg === '-e') {
|
|
94
|
-
if (++i >= argv.length) throw new UsageError('-e 后面要写
|
|
99
|
+
if (++i >= argv.length) throw new UsageError('-e 后面要写 变量=<标识>[#<字段>]')
|
|
95
100
|
const { name, identifier, field } = parseVariable(argv[i])
|
|
96
101
|
if (variables.has(name)) throw new UsageError(`变量 ${name} 写了两次`)
|
|
97
|
-
const ref = `${identifier}#${field}`
|
|
102
|
+
const ref = `${identifier}#${field ?? ''}`
|
|
98
103
|
if (!refIndex.has(ref)) {
|
|
99
104
|
refIndex.set(ref, refs.length)
|
|
100
|
-
refs.push({ identifier, field })
|
|
105
|
+
refs.push(field === undefined ? { identifier } : { identifier, field })
|
|
101
106
|
}
|
|
102
107
|
variables.set(name, refIndex.get(ref))
|
|
103
108
|
} else if (arg === '--purpose' || arg.startsWith('--purpose=')) {
|
|
@@ -113,22 +118,32 @@ export function parseRunArgs(argv) {
|
|
|
113
118
|
const command = argv[i + 1]
|
|
114
119
|
if (!command) throw new UsageError('-- 后面要写命令')
|
|
115
120
|
if (variables.size === 0) throw new UsageError('至少要写一个 -e')
|
|
116
|
-
if (refs.length > MAX_REFS) throw new UsageError(`一次最多取 ${MAX_REFS}
|
|
121
|
+
if (refs.length > MAX_REFS) throw new UsageError(`一次最多取 ${MAX_REFS} 项`)
|
|
117
122
|
return { refs, variables: [...variables], purpose, command, args: argv.slice(i + 2) }
|
|
118
123
|
}
|
|
119
124
|
|
|
120
125
|
// 等号后面写错时只说格式,不复述写的内容:那里可能误填了值本身
|
|
121
126
|
function parseVariable(spec) {
|
|
122
127
|
const eq = spec.indexOf('=')
|
|
123
|
-
if (eq <= 0) throw new UsageError('-e 要写成
|
|
128
|
+
if (eq <= 0) throw new UsageError('-e 要写成 变量=<标识>[#<字段>]')
|
|
124
129
|
const name = spec.slice(0, eq)
|
|
125
130
|
if (!VARIABLE.test(name)) {
|
|
126
131
|
throw new UsageError(`变量名 ${name} 只能用字母、数字和下划线,不能以数字开头`)
|
|
127
132
|
}
|
|
128
|
-
const
|
|
129
|
-
|
|
133
|
+
const raw = spec.slice(eq + 1)
|
|
134
|
+
const hash = raw.indexOf('#')
|
|
135
|
+
if (hash === -1) {
|
|
136
|
+
if (!SLUG.test(raw)) {
|
|
137
|
+
throw new UsageError(
|
|
138
|
+
`${name} 要写成 ${name}=<标识> 或 ${name}=<标识>#<字段>;标识只用小写字母、数字、.、_ 和 -,以字母或数字开头,最长 64 个字符`,
|
|
139
|
+
)
|
|
140
|
+
}
|
|
141
|
+
return { name, identifier: raw, field: undefined }
|
|
142
|
+
}
|
|
143
|
+
const [identifier, field, ...rest] = raw.split('#')
|
|
144
|
+
if (rest.length > 0 || !SLUG.test(identifier) || !FIELD.test(field ?? '')) {
|
|
130
145
|
throw new UsageError(
|
|
131
|
-
`${name} 要写成 ${name}
|
|
146
|
+
`${name} 要写成 ${name}=<标识> 或 ${name}=<标识>#<字段>;标识只用小写字母、数字、.、_ 和 -,字段名只用小写字母、数字、_ 和 -,以字母或数字开头,最长 64 个字符`,
|
|
132
147
|
)
|
|
133
148
|
}
|
|
134
149
|
return { name, identifier, field }
|
|
@@ -142,14 +157,10 @@ function parsePurpose(value) {
|
|
|
142
157
|
return text || undefined
|
|
143
158
|
}
|
|
144
159
|
|
|
145
|
-
//
|
|
160
|
+
// 服务端的错误文字原样给出,去掉控制与格式字符;万一带着访问密钥也盖掉
|
|
146
161
|
function serverError(data, status, key) {
|
|
147
162
|
const text = typeof data?.error === 'string' ? data.error : ''
|
|
148
|
-
const clean = text
|
|
149
|
-
.split(key)
|
|
150
|
-
.join('***')
|
|
151
|
-
.replace(/\p{Cc}+/gu, ' ')
|
|
152
|
-
.trim()
|
|
163
|
+
const clean = plain(key ? text.split(key).join('***') : text)
|
|
153
164
|
return clean || `Kioku 返回 HTTP ${status}`
|
|
154
165
|
}
|
|
155
166
|
|
|
@@ -157,25 +168,33 @@ function serverError(data, status, key) {
|
|
|
157
168
|
// 格式不对的项跳过,不因为提示让整次失败。打印之前去掉控制字符
|
|
158
169
|
function expiredOf(data) {
|
|
159
170
|
if (!Array.isArray(data?.expired)) return []
|
|
160
|
-
const clean = (text) => text.replace(/\p{Cc}+/gu, ' ').trim()
|
|
161
171
|
return data.expired.flatMap((item) =>
|
|
162
172
|
typeof item?.identifier === 'string' && typeof item.expiresAt === 'string'
|
|
163
|
-
? [{ identifier:
|
|
173
|
+
? [{ identifier: plain(item.identifier), expiresAt: plain(item.expiresAt) }]
|
|
164
174
|
: [],
|
|
165
175
|
)
|
|
166
176
|
}
|
|
167
177
|
|
|
168
|
-
// 按 refs 的顺序取出响应里的值;对不上时为 null
|
|
178
|
+
// 按 refs 的顺序取出响应里的值;对不上时为 null。
|
|
179
|
+
// 请求省略 field 时服务端回 field: 'value';同一个标识同时请求裸标识与 #value 时按响应顺序依次取出
|
|
169
180
|
function valuesOf(data, refs) {
|
|
170
181
|
if (!Array.isArray(data?.values) || data.values.length !== refs.length) return null
|
|
171
|
-
const
|
|
182
|
+
const queues = new Map()
|
|
172
183
|
for (const item of data.values) {
|
|
173
184
|
if (typeof item?.identifier !== 'string' || typeof item.field !== 'string') return null
|
|
174
185
|
if (typeof item.value !== 'string') return null
|
|
175
|
-
|
|
186
|
+
const key = `${item.identifier}#${item.field}`
|
|
187
|
+
const list = queues.get(key)
|
|
188
|
+
if (list) list.push(item.value)
|
|
189
|
+
else queues.set(key, [item.value])
|
|
190
|
+
}
|
|
191
|
+
const values = []
|
|
192
|
+
for (const r of refs) {
|
|
193
|
+
const list = queues.get(`${r.identifier}#${r.field ?? 'value'}`)
|
|
194
|
+
if (!list || list.length === 0) return null
|
|
195
|
+
values.push(list.shift())
|
|
176
196
|
}
|
|
177
|
-
|
|
178
|
-
return values.every((v) => v !== undefined) ? values : null
|
|
197
|
+
return values
|
|
179
198
|
}
|
|
180
199
|
|
|
181
200
|
// 一次请求取全部值:任何一项取不到时整次失败,响应里不带值。连同已到期的凭据一起返回
|
|
@@ -204,6 +223,13 @@ async function resolveValues({ url, key }, refs, purpose) {
|
|
|
204
223
|
} catch {
|
|
205
224
|
// 不是 JSON 时按没有错误文字处理
|
|
206
225
|
}
|
|
226
|
+
// 401 与 503 database_unavailable 优先用这边的清晰提示(服务端原文若误带出当前密钥则留待打码)
|
|
227
|
+
const rejected = res.ok ? null : rejectionOf(res.status, data)
|
|
228
|
+
if (rejected instanceof DatabaseUnavailable) throw rejected
|
|
229
|
+
if (rejected instanceof KeyRejected) {
|
|
230
|
+
const echoed = typeof data?.error === 'string' && data.error.includes(key)
|
|
231
|
+
if (!echoed) throw rejected
|
|
232
|
+
}
|
|
207
233
|
if (!res.ok) throw new KiokuFailure(serverError(data, res.status, key))
|
|
208
234
|
const values = valuesOf(data, refs)
|
|
209
235
|
if (!values) throw new KiokuFailure('Kioku 的响应格式不对')
|
|
@@ -356,11 +382,19 @@ export async function run(argv) {
|
|
|
356
382
|
const withNul = refs.findIndex((_, i) => values[i].includes('\0'))
|
|
357
383
|
if (withNul !== -1) {
|
|
358
384
|
const { identifier, field } = refs[withNul]
|
|
359
|
-
|
|
385
|
+
const label = field === undefined ? identifier : `${identifier}#${field}`
|
|
386
|
+
process.stderr.write(`kioku:${label} 的值含有空字符,放不进环境变量\n`)
|
|
360
387
|
return 2
|
|
361
388
|
}
|
|
362
389
|
const env = { ...process.env }
|
|
363
|
-
|
|
390
|
+
if (process.platform === 'win32') {
|
|
391
|
+
const blocked = new Set(KEY_VARIABLES.map((n) => n.toUpperCase()))
|
|
392
|
+
for (const k of Object.keys(env)) {
|
|
393
|
+
if (blocked.has(k.toUpperCase())) delete env[k]
|
|
394
|
+
}
|
|
395
|
+
} else {
|
|
396
|
+
for (const name of KEY_VARIABLES) delete env[name]
|
|
397
|
+
}
|
|
364
398
|
for (const [name, index] of variables) env[name] = values[index]
|
|
365
399
|
const short = variables.filter(([, index]) => !redactable(values[index])).map(([name]) => name)
|
|
366
400
|
if (short.length > 0) process.stderr.write(`kioku:${short.join('、')} 的值太短,输出里不打码\n`)
|