@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`)
|
|
@@ -10,6 +10,7 @@ import { failureText, KiokuFailure } from '../lib/http.mjs'
|
|
|
10
10
|
import {
|
|
11
11
|
clip,
|
|
12
12
|
contextOf,
|
|
13
|
+
deviceKeyOf,
|
|
13
14
|
MAX_PROMPT,
|
|
14
15
|
MAX_REPLY,
|
|
15
16
|
MAX_SESSION_ID,
|
|
@@ -51,13 +52,14 @@ function pendingFile(env, sessionId) {
|
|
|
51
52
|
return join(pendingDir(env), `${PENDING_PREFIX}${sessionId}.json`)
|
|
52
53
|
}
|
|
53
54
|
|
|
54
|
-
async function savePending(env, sessionId, prompt) {
|
|
55
|
+
async function savePending(env, sessionId, prompt, project) {
|
|
55
56
|
const file = pendingFile(env, sessionId)
|
|
56
57
|
if (!file) return
|
|
57
58
|
await mkdir(pendingDir(env), { recursive: true, mode: 0o700 })
|
|
58
59
|
const temp = `${file}.${randomUUID()}.tmp`
|
|
59
60
|
try {
|
|
60
|
-
|
|
61
|
+
const data = Object.keys(project ?? {}).length ? { prompt, project } : { prompt }
|
|
62
|
+
await writeFile(temp, JSON.stringify(data), { mode: 0o600, flag: 'wx' })
|
|
61
63
|
await rename(temp, file)
|
|
62
64
|
} catch (err) {
|
|
63
65
|
await rm(temp, { force: true }).catch(() => {})
|
|
@@ -69,8 +71,15 @@ async function takePending(env, sessionId) {
|
|
|
69
71
|
const file = pendingFile(env, sessionId)
|
|
70
72
|
if (!file) return null
|
|
71
73
|
try {
|
|
72
|
-
const
|
|
73
|
-
|
|
74
|
+
const parsed = JSON.parse(await readFile(file, 'utf8'))
|
|
75
|
+
if (typeof parsed?.prompt !== 'string' || !parsed.prompt) return null
|
|
76
|
+
return {
|
|
77
|
+
user: parsed.prompt,
|
|
78
|
+
project:
|
|
79
|
+
parsed.project && typeof parsed.project === 'object' && !Array.isArray(parsed.project)
|
|
80
|
+
? parsed.project
|
|
81
|
+
: undefined,
|
|
82
|
+
}
|
|
74
83
|
} catch {
|
|
75
84
|
return null
|
|
76
85
|
} finally {
|
|
@@ -108,7 +117,7 @@ export async function forwardGeminiEvent(event, rawStdin, env = process.env) {
|
|
|
108
117
|
}
|
|
109
118
|
if (!profile) {
|
|
110
119
|
if (event === 'session.start') {
|
|
111
|
-
return `Kioku
|
|
120
|
+
return `Kioku 插件尚未配置服务地址和访问密钥,长期记忆不可用:${SETUP_HINT}。`
|
|
112
121
|
}
|
|
113
122
|
return null
|
|
114
123
|
}
|
|
@@ -116,14 +125,23 @@ export async function forwardGeminiEvent(event, rawStdin, env = process.env) {
|
|
|
116
125
|
const { url: base, key } = profile
|
|
117
126
|
const sessionId =
|
|
118
127
|
typeof input.session_id === 'string' && input.session_id
|
|
119
|
-
? input.session_id
|
|
128
|
+
? clip(input.session_id, MAX_SESSION_ID)
|
|
120
129
|
: undefined
|
|
121
|
-
const
|
|
130
|
+
const explicitCwd = typeof input.cwd === 'string' && input.cwd ? input.cwd : ''
|
|
131
|
+
const detectedProject = projectOf(explicitCwd || process.cwd())
|
|
132
|
+
const deviceKey = deviceKeyOf(env)
|
|
133
|
+
const body = {
|
|
134
|
+
event,
|
|
135
|
+
...(sessionId ? { sessionId } : {}),
|
|
136
|
+
...(deviceKey ? { deviceKey } : {}),
|
|
137
|
+
}
|
|
122
138
|
|
|
123
139
|
if (event === 'turn.end') {
|
|
124
140
|
if (input.stop_hook_active === true) return null
|
|
125
141
|
const direct = typeof input.prompt === 'string' ? input.prompt.trim() : ''
|
|
126
|
-
|
|
142
|
+
// 总是消费并清理本轮暂存,避免已传入直传 prompt 时暂存文件残留并保留项目上下文
|
|
143
|
+
const pending = await takePending(env, sessionId)
|
|
144
|
+
const user = direct || pending?.user
|
|
127
145
|
const reply =
|
|
128
146
|
typeof input.prompt_response === 'string'
|
|
129
147
|
? input.prompt_response
|
|
@@ -131,23 +149,21 @@ export async function forwardGeminiEvent(event, rawStdin, env = process.env) {
|
|
|
131
149
|
? input.last_assistant_message
|
|
132
150
|
: ''
|
|
133
151
|
if (!sessionId || !user) return null
|
|
152
|
+
const project = explicitCwd ? detectedProject : (pending?.project ?? detectedProject)
|
|
153
|
+
if (Object.keys(project).length) body.project = project
|
|
134
154
|
body.user = clip(user, MAX_PROMPT)
|
|
135
155
|
body.reply = clip(reply.trim(), MAX_REPLY)
|
|
136
156
|
await postEvent(base, key, body, timeout)
|
|
137
157
|
return null
|
|
138
158
|
}
|
|
139
159
|
|
|
140
|
-
if (
|
|
141
|
-
const cwd = typeof input.cwd === 'string' && input.cwd ? input.cwd : process.cwd()
|
|
142
|
-
const project = projectOf(cwd)
|
|
143
|
-
if (Object.keys(project).length) body.project = project
|
|
144
|
-
}
|
|
160
|
+
if (Object.keys(detectedProject).length) body.project = detectedProject
|
|
145
161
|
|
|
146
162
|
if (event === 'prompt.submit') {
|
|
147
163
|
const prompt = typeof input.prompt === 'string' ? input.prompt.trim() : ''
|
|
148
164
|
if (!prompt) return null
|
|
149
165
|
body.prompt = clip(prompt, MAX_PROMPT)
|
|
150
|
-
await savePending(env, sessionId, body.prompt).catch(() => {})
|
|
166
|
+
await savePending(env, sessionId, body.prompt, detectedProject).catch(() => {})
|
|
151
167
|
}
|
|
152
168
|
|
|
153
169
|
const res = await postEvent(base, key, body, timeout)
|
|
@@ -10,9 +10,15 @@ import { join, win32 } from 'node:path'
|
|
|
10
10
|
|
|
11
11
|
import { KiokuFailure } from './http.mjs'
|
|
12
12
|
|
|
13
|
+
const WINDOWS_APPS_STUB = /[\\/]Microsoft[\\/]WindowsApps[\\/][^\\/]+$/i
|
|
14
|
+
|
|
13
15
|
const isFile = (file) => {
|
|
14
16
|
try {
|
|
15
|
-
|
|
17
|
+
const st = statSync(file)
|
|
18
|
+
if (!st.isFile()) return false
|
|
19
|
+
// 未安装对应商店应用时 WindowsApps 目录里的执行别名是 0 字节空壳,跳过它免得误认或拉起商店弹窗
|
|
20
|
+
if (WINDOWS_APPS_STUB.test(file) && st.size === 0) return false
|
|
21
|
+
return true
|
|
16
22
|
} catch {
|
|
17
23
|
return false
|
|
18
24
|
}
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
import { readFile, utimes } from 'node:fs/promises'
|
|
4
4
|
|
|
5
5
|
import { errorKind, keyFormatError, KiokuFailure } from './http.mjs'
|
|
6
|
+
import { serverUrlProblem } from './profile.mjs'
|
|
6
7
|
|
|
7
8
|
const NOT_CONFIGURED =
|
|
8
9
|
'缺少 Kioku 的地址或访问密钥:在 Claude Code 里启用 kioku 插件、填好配置后新开会话,或者设置 KIOKU_SERVER_URL 与 KIOKU_API_KEY'
|
|
@@ -35,15 +36,8 @@ export async function loadConfig(env) {
|
|
|
35
36
|
`无法读取访问密钥文件 ${file}(${fileProblem}):新开会话,或者设置 KIOKU_API_KEY`,
|
|
36
37
|
)
|
|
37
38
|
}
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
protocol = new URL(url).protocol
|
|
41
|
-
} catch {
|
|
42
|
-
throw new KiokuFailure('KIOKU_SERVER_URL 不是有效的地址')
|
|
43
|
-
}
|
|
44
|
-
if (protocol !== 'http:' && protocol !== 'https:') {
|
|
45
|
-
throw new KiokuFailure('KIOKU_SERVER_URL 要以 http:// 或 https:// 开头')
|
|
46
|
-
}
|
|
39
|
+
const urlProblem = serverUrlProblem(url)
|
|
40
|
+
if (urlProblem) throw new KiokuFailure(urlProblem.replace(/^服务地址/, 'KIOKU_SERVER_URL '))
|
|
47
41
|
const problem = keyFormatError(key)
|
|
48
42
|
if (problem) throw new KiokuFailure(problem)
|
|
49
43
|
return { url, key }
|
|
@@ -55,3 +55,48 @@ export function isRedirect(status) {
|
|
|
55
55
|
export function failureText(err) {
|
|
56
56
|
return err instanceof KiokuFailure ? err.message : errorKind(err)
|
|
57
57
|
}
|
|
58
|
+
|
|
59
|
+
// 服务端在响应体里给的错误码(与服务端 contracts 的常量一致):
|
|
60
|
+
// database_unavailable 表示数据库尚未配置或暂时无法连接(503)
|
|
61
|
+
export const DATABASE_UNAVAILABLE_CODE = 'database_unavailable'
|
|
62
|
+
|
|
63
|
+
export const INVALID_KEY_TEXT = '访问密钥无效或已吊销'
|
|
64
|
+
export const DATABASE_UNAVAILABLE_TEXT = 'Kioku 的数据库暂时无法连接,请稍后重试'
|
|
65
|
+
|
|
66
|
+
// 服务端明说访问密钥不能用(401):和连不上、响应不对分开
|
|
67
|
+
export class KeyRejected extends KiokuFailure {
|
|
68
|
+
constructor() {
|
|
69
|
+
super(INVALID_KEY_TEXT)
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// 服务端数据库尚未配置或暂时无法连接(503 database_unavailable)
|
|
74
|
+
export class DatabaseUnavailable extends KiokuFailure {
|
|
75
|
+
constructor() {
|
|
76
|
+
super(DATABASE_UNAVAILABLE_TEXT)
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// 响应体里的错误码;没有、或者不像错误码时为 null(服务端写的文字不原样拿来用)
|
|
81
|
+
export function errorCodeOf(data) {
|
|
82
|
+
const code = data?.code
|
|
83
|
+
return typeof code === 'string' && /^[a-z][a-z0-9_]{0,63}$/.test(code) ? code : null
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// 401 与带 database_unavailable 的 503 的统一解读:返回要抛的失败,别的状态返回 null
|
|
87
|
+
export function rejectionOf(status, data) {
|
|
88
|
+
if (status === 401) return new KeyRejected()
|
|
89
|
+
if (status === 503 && errorCodeOf(data) === DATABASE_UNAVAILABLE_CODE) {
|
|
90
|
+
return new DatabaseUnavailable()
|
|
91
|
+
}
|
|
92
|
+
return null
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// 响应文字按 JSON 读,读不懂时为 null
|
|
96
|
+
export function jsonOrNull(text) {
|
|
97
|
+
try {
|
|
98
|
+
return JSON.parse(text)
|
|
99
|
+
} catch {
|
|
100
|
+
return null
|
|
101
|
+
}
|
|
102
|
+
}
|
|
@@ -5,7 +5,7 @@ import { parseRunArgs, run, USAGE, UsageError } from './run.mjs'
|
|
|
5
5
|
|
|
6
6
|
export { parseRunArgs, run, USAGE, UsageError }
|
|
7
7
|
|
|
8
|
-
const OVERVIEW = `用法:kioku run -e
|
|
8
|
+
const OVERVIEW = `用法:kioku run -e 变量=<标识>[#<字段>] [-e …] [--purpose <用途>] -- <命令> [参数…]
|
|
9
9
|
|
|
10
10
|
插件目录内置的命令行入口仅包含 kioku run(向 Kioku 取凭据,放进环境变量并打码输出)。
|
|
11
11
|
向导、接入管理与记忆读写等完整功能见 @kioku-memory/cli:
|
|
@@ -19,6 +19,7 @@ const OVERVIEW = `用法:kioku run -e 变量=<标识>#<字段> [-e …] [--pur
|
|
|
19
19
|
const FULL_CLI_COMMANDS = new Set([
|
|
20
20
|
'connect',
|
|
21
21
|
'disconnect',
|
|
22
|
+
'migrate',
|
|
22
23
|
'upgrade',
|
|
23
24
|
'status',
|
|
24
25
|
'login',
|
|
@@ -33,6 +34,10 @@ const FULL_CLI_COMMANDS = new Set([
|
|
|
33
34
|
'get',
|
|
34
35
|
'ls',
|
|
35
36
|
'add',
|
|
37
|
+
'edit',
|
|
38
|
+
'delete',
|
|
39
|
+
'rm',
|
|
40
|
+
'boot',
|
|
36
41
|
])
|
|
37
42
|
|
|
38
43
|
export async function main(argv) {
|
|
@@ -4,9 +4,17 @@
|
|
|
4
4
|
// 也不跟着跳转走,访问密钥只发给配置的地址
|
|
5
5
|
|
|
6
6
|
import { execFile, execFileSync } from 'node:child_process'
|
|
7
|
+
import { hostname } from 'node:os'
|
|
7
8
|
import { basename } from 'node:path'
|
|
8
9
|
|
|
9
|
-
import {
|
|
10
|
+
import {
|
|
11
|
+
fetchFailure,
|
|
12
|
+
isRedirect,
|
|
13
|
+
keyFormatError,
|
|
14
|
+
KiokuFailure,
|
|
15
|
+
redirectError,
|
|
16
|
+
rejectionOf,
|
|
17
|
+
} from './http.mjs'
|
|
10
18
|
|
|
11
19
|
// 各事件等待服务端的上限(毫秒),要比平台给钩子的时限短
|
|
12
20
|
export const TIMEOUTS = { 'session.start': 8000, 'prompt.submit': 5000, 'turn.end': 5000 }
|
|
@@ -16,6 +24,29 @@ export const MAX_REPLY = 20_000
|
|
|
16
24
|
export const MAX_SESSION_ID = 200
|
|
17
25
|
const MAX_NAME = 128
|
|
18
26
|
|
|
27
|
+
function stripControl(text) {
|
|
28
|
+
let out = ''
|
|
29
|
+
for (const ch of text) {
|
|
30
|
+
const code = ch.charCodeAt(0)
|
|
31
|
+
if (code >= 0x20 && code !== 0x7f && (code < 0x80 || code > 0x9f)) out += ch
|
|
32
|
+
}
|
|
33
|
+
return out
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function deviceKeyOf(env = process.env) {
|
|
37
|
+
const override = typeof env?.KIOKU_DEVICE_KEY === 'string' ? env.KIOKU_DEVICE_KEY : ''
|
|
38
|
+
let raw = override
|
|
39
|
+
if (!stripControl(raw).trim()) {
|
|
40
|
+
try {
|
|
41
|
+
raw = hostname()
|
|
42
|
+
} catch {
|
|
43
|
+
raw = ''
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
const clean = clip(stripControl(raw).trim(), MAX_NAME).trim()
|
|
47
|
+
return clean || undefined
|
|
48
|
+
}
|
|
49
|
+
|
|
19
50
|
// 配置写错了:访问密钥格式不对(kind 为 key),或者服务地址返回跳转(kind 为 url)。
|
|
20
51
|
// 和没有配置一样,平台可以在会话开始时提示一次;文字不带访问密钥
|
|
21
52
|
export class Misconfigured extends KiokuFailure {
|
|
@@ -47,7 +78,7 @@ export function clip(text, max) {
|
|
|
47
78
|
export function projectOf(cwd) {
|
|
48
79
|
const project = {}
|
|
49
80
|
const dirName = basename(cwd)
|
|
50
|
-
if (dirName) project.dirName = dirName
|
|
81
|
+
if (dirName) project.dirName = clip(dirName, MAX_NAME)
|
|
51
82
|
try {
|
|
52
83
|
const remote = execFileSync('git', ['-C', cwd, 'remote', 'get-url', 'origin'], {
|
|
53
84
|
encoding: 'utf8',
|
|
@@ -55,7 +86,7 @@ export function projectOf(cwd) {
|
|
|
55
86
|
stdio: ['ignore', 'pipe', 'ignore'],
|
|
56
87
|
}).trim()
|
|
57
88
|
const repoName = /([^/:]+?)(?:\.git)?$/.exec(remote)?.[1]
|
|
58
|
-
if (repoName) project.repoName = repoName
|
|
89
|
+
if (repoName) project.repoName = clip(repoName, MAX_NAME)
|
|
59
90
|
} catch {
|
|
60
91
|
// 不是 git 仓库或没有 origin
|
|
61
92
|
}
|
|
@@ -66,7 +97,7 @@ export function projectOf(cwd) {
|
|
|
66
97
|
export function projectOfAsync(cwd) {
|
|
67
98
|
const project = {}
|
|
68
99
|
const dirName = basename(cwd)
|
|
69
|
-
if (dirName) project.dirName = dirName
|
|
100
|
+
if (dirName) project.dirName = clip(dirName, MAX_NAME)
|
|
70
101
|
return new Promise((resolve) => {
|
|
71
102
|
execFile(
|
|
72
103
|
'git',
|
|
@@ -74,7 +105,7 @@ export function projectOfAsync(cwd) {
|
|
|
74
105
|
{ encoding: 'utf8', timeout: 1500 },
|
|
75
106
|
(err, stdout) => {
|
|
76
107
|
const repoName = err ? undefined : /([^/:]+?)(?:\.git)?$/.exec(stdout.trim())?.[1]
|
|
77
|
-
if (repoName) project.repoName = repoName
|
|
108
|
+
if (repoName) project.repoName = clip(repoName, MAX_NAME)
|
|
78
109
|
resolve(project)
|
|
79
110
|
},
|
|
80
111
|
)
|
|
@@ -123,6 +154,10 @@ export async function postEvent(base, key, body, timeout, signal) {
|
|
|
123
154
|
if (isRedirect(res.status)) {
|
|
124
155
|
throw new Misconfigured(redirectError(res.status, res.headers.get('location'), base), 'url')
|
|
125
156
|
}
|
|
157
|
+
if (res.status === 401 || res.status === 503) {
|
|
158
|
+
const rejected = rejectionOf(res.status, await res.json().catch(() => null))
|
|
159
|
+
if (rejected) throw rejected
|
|
160
|
+
}
|
|
126
161
|
if (!res.ok) throw new KiokuFailure(`HTTP ${res.status}`)
|
|
127
162
|
return res
|
|
128
163
|
}
|