@kioku-memory/openclaw 0.0.0-stage → 0.0.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/lib/import.mjs ADDED
@@ -0,0 +1,262 @@
1
+ // kioku import:把平台自带的本地长期记忆迁进 Kioku。先读本地文件出一份计划(每条放到哪个坐标),
2
+ // 和 Kioku 里已有的比过之后列出来,确认了才写。坐标由来源决定,所以重复运行不会重复写:
3
+ // 已经有、内容一样的跳过;已经有、内容不一样的不覆盖(可能在 Kioku 里改过),要覆盖得明说。
4
+ // 本地的文件不删、不改
5
+
6
+ import { whoami } from './api.mjs'
7
+ import { loadConfig } from './config.mjs'
8
+ import { fetchFailure, isRedirect, KiokuFailure, redirectError } from './http.mjs'
9
+ import { platformNames, PLATFORMS } from './platforms.mjs'
10
+ import { sourceNames, SOURCES, UNSUPPORTED_SOURCES } from './sources.mjs'
11
+ import { plain, shownUrl } from './text.mjs'
12
+ import { UsageError } from './usage.mjs'
13
+
14
+ export const IMPORT_USAGE = `用法:kioku import --from <来源> [--path <目录>] [--platform <平台>] [--dry-run] [--yes] [--overwrite]
15
+
16
+ 把平台自带的本地长期记忆迁进 Kioku:先列出每条会放到哪个坐标,确认之后才写。
17
+
18
+ --from <来源> ${sourceNames()}
19
+ --path <目录> 不用默认的位置时指明(Claude Code 是 projects 目录或某个项目的 memory 目录)
20
+ --platform <平台> 用 kioku setup 给这个平台配好的地址与访问密钥(codex、pi、hermes、openclaw、dsh);不写时读环境变量
21
+ --dry-run 只列出计划,不写
22
+ --yes 不问,直接写(不在终端里运行时要带上)
23
+ --overwrite Kioku 里同一个坐标已经有、内容不一样的也覆盖(默认跳过)
24
+
25
+ 本地的文件不删、不改。重复运行不会重复写:已经迁过、内容没变的会跳过。
26
+ 疑似明文凭据的不写,列出是哪个文件的哪一行:先把值存成凭据,或者从文件里去掉再迁。
27
+ 地址与访问密钥读 KIOKU_SERVER_URL 与 KIOKU_API_KEY(Claude Code 的会话里已经配好),或者用 --platform 指明。
28
+ 记忆迁进这个访问密钥所属的应用。
29
+ 指令文件(AGENTS.md、CLAUDE.md)不是记忆,不迁。
30
+ `
31
+
32
+ const TIMEOUT = 15_000
33
+
34
+ export function parseImportArgs(argv) {
35
+ const options = {
36
+ from: undefined,
37
+ path: undefined,
38
+ platform: undefined,
39
+ dryRun: false,
40
+ yes: false,
41
+ overwrite: false,
42
+ }
43
+ for (let i = 0; i < argv.length; i++) {
44
+ const arg = argv[i]
45
+ if (arg === '--dry-run') options.dryRun = true
46
+ else if (arg === '--yes') options.yes = true
47
+ else if (arg === '--overwrite') options.overwrite = true
48
+ else if (arg === '--from' || arg === '--path' || arg === '--platform') {
49
+ const value = argv[++i]
50
+ if (!value) throw new UsageError(`${arg} 后面要写值`)
51
+ options[arg.slice(2)] = value
52
+ } else throw new UsageError(`不认识的参数 ${arg}`)
53
+ }
54
+ if (!options.from) throw new UsageError('要写来源:--from <来源>')
55
+ if (Object.hasOwn(UNSUPPORTED_SOURCES, options.from)) {
56
+ throw new KiokuFailure(UNSUPPORTED_SOURCES[options.from])
57
+ }
58
+ if (!Object.hasOwn(SOURCES, options.from)) {
59
+ throw new UsageError(`不认识的来源 ${options.from},可以用的:${sourceNames()}`)
60
+ }
61
+ if (options.platform !== undefined && !PLATFORMS[options.platform]?.readConfig) {
62
+ throw new UsageError(
63
+ `--platform 只收用 kioku setup 写下配置的平台,可以用的:${platformNames()}`,
64
+ )
65
+ }
66
+ return options
67
+ }
68
+
69
+ async function request({ url, key }, method, path, body) {
70
+ let res
71
+ let data
72
+ try {
73
+ res = await fetch(`${url}${path}`, {
74
+ method,
75
+ headers: {
76
+ authorization: `Bearer ${key}`,
77
+ ...(body ? { 'content-type': 'application/json' } : {}),
78
+ },
79
+ ...(body ? { body: JSON.stringify(body) } : {}),
80
+ // 不跟着跳转走:访问密钥只发给配置的地址
81
+ redirect: 'manual',
82
+ signal: AbortSignal.timeout(TIMEOUT),
83
+ })
84
+ data = await res.json().catch(() => null)
85
+ } catch (err) {
86
+ throw new KiokuFailure(fetchFailure(err, TIMEOUT))
87
+ }
88
+ if (isRedirect(res.status)) {
89
+ throw new KiokuFailure(redirectError(res.status, res.headers.get('location'), url))
90
+ }
91
+ return { status: res.status, data }
92
+ }
93
+
94
+ // 服务端的错误文字压成一行;万一带着访问密钥也盖掉
95
+ function serverText(data, status, key) {
96
+ const text = typeof data?.error === 'string' ? data.error.split(key).join('***') : ''
97
+ return plain(text) || `HTTP ${status}`
98
+ }
99
+
100
+ // 和 Kioku 里现有的比:new 没有,same 有且正文一样,differs 有但不一样(含读不到正文的机密)
101
+ async function compare(config, item) {
102
+ const { status, data } = await request(
103
+ config,
104
+ 'GET',
105
+ `/v1/memories?uri=${encodeURIComponent(item.uri)}`,
106
+ )
107
+ if (status === 404) return { ...item, state: 'new' }
108
+ if (status !== 200)
109
+ return { ...item, state: 'failed', reason: serverText(data, status, config.key) }
110
+ const same = typeof data?.content === 'string' && data.content.trim() === item.content
111
+ return { ...item, state: same ? 'same' : 'differs', version: data?.version, id: data?.id }
112
+ }
113
+
114
+ // 写一条:新建,或者覆盖已有的。返回 { ok } 或 { ok: false, reason, plaintext }
115
+ async function write(config, item) {
116
+ const fields = {
117
+ uri: item.uri,
118
+ title: item.title,
119
+ content: item.content,
120
+ ...(item.disclosure ? { disclosure: item.disclosure } : {}),
121
+ }
122
+ const { status, data } =
123
+ item.state === 'differs'
124
+ ? await request(config, 'PATCH', '/v1/memories', {
125
+ ...fields,
126
+ ...(Number.isInteger(item.version) ? { expectedVersion: item.version } : {}),
127
+ ...(item.id ? { expectedId: item.id } : {}),
128
+ })
129
+ : await request(config, 'POST', '/v1/memories', fields)
130
+ if (status === 200 || status === 201) return { ok: true }
131
+ const plaintext = Array.isArray(data?.plaintext) ? data.plaintext : null
132
+ return { ok: false, reason: serverText(data, status, config.key), plaintext }
133
+ }
134
+
135
+ const KINDS = { new: '新建', same: '已有,内容一样', differs: '已有,内容不一样' }
136
+
137
+ // 问一句是或否;只认 y 开头的回答
138
+ async function confirm(question, { stdin, out }) {
139
+ out.write(question)
140
+ for await (const chunk of stdin) {
141
+ return /^\s*y/i.test(chunk.toString('utf8'))
142
+ }
143
+ return false
144
+ }
145
+
146
+ export async function importMemories(
147
+ argv,
148
+ { env = process.env, out = process.stdout, stdin = process.stdin } = {},
149
+ ) {
150
+ const options = parseImportArgs(argv)
151
+ const source = SOURCES[options.from]
152
+ // 地址与访问密钥:指明了平台就用 kioku setup 给它写下的,否则读环境变量
153
+ let config
154
+ if (options.platform) {
155
+ config = await PLATFORMS[options.platform].readConfig(env)
156
+ if (!config) {
157
+ throw new KiokuFailure(
158
+ `还没有给 ${options.platform} 配过:先运行 kioku setup ${options.platform}`,
159
+ )
160
+ }
161
+ } else config = await loadConfig(env)
162
+ const who = await whoami(config)
163
+ out.write(
164
+ `Kioku:${shownUrl(config.url)},应用 ${plain(who.app.name)}(${plain(who.app.slug)})\n`,
165
+ )
166
+
167
+ const { root, found, entries } = await source.read({
168
+ env,
169
+ path: options.path,
170
+ app: who.app.slug,
171
+ })
172
+ if (!found)
173
+ throw new KiokuFailure(`没有找到${source.name}:${plain(root)} 不是目录,用 --path 指明位置`)
174
+ out.write(`来源:${source.name}(${plain(root)})\n`)
175
+ if (!entries.length) {
176
+ out.write('没有可以迁的记忆\n')
177
+ return 0
178
+ }
179
+
180
+ // 两条落到同一个坐标的(名字规整之后撞了)只留第一条
181
+ const seen = new Set()
182
+ const usable = []
183
+ const skipped = []
184
+ for (const item of entries) {
185
+ if (item.skipped) skipped.push(item)
186
+ else if (seen.has(item.uri))
187
+ skipped.push({ ...item, skipped: `和前面的一条落到同一个坐标 ${item.uri}` })
188
+ else {
189
+ seen.add(item.uri)
190
+ usable.push(item)
191
+ }
192
+ }
193
+ const compared = []
194
+ for (const item of usable) compared.push(await compare(config, item))
195
+
196
+ out.write('\n')
197
+ for (const item of compared) {
198
+ const kind = item.state === 'failed' ? `读取失败(${item.reason})` : KINDS[item.state]
199
+ out.write(`${kind} ${item.uri}\n ${plain(item.title)}\n ← ${plain(item.source)}\n`)
200
+ }
201
+ for (const item of skipped) out.write(`不迁 ${plain(item.source)}\n ${item.skipped}\n`)
202
+
203
+ const count = (state) => compared.filter((item) => item.state === state).length
204
+ const todo = compared.filter(
205
+ (item) => item.state === 'new' || (item.state === 'differs' && options.overwrite),
206
+ )
207
+ out.write(
208
+ `\n新建 ${count('new')} 条,已有且一样 ${count('same')} 条,已有但不一样 ${count('differs')} 条` +
209
+ `(${options.overwrite ? '覆盖' : '跳过,要覆盖加 --overwrite'}),不迁 ${skipped.length} 条\n`,
210
+ )
211
+ if (options.dryRun) {
212
+ out.write('没有写入(--dry-run)\n')
213
+ return 0
214
+ }
215
+ if (!todo.length) {
216
+ out.write('没有要写的\n')
217
+ return compared.some((item) => item.state === 'failed') ? 1 : 0
218
+ }
219
+ if (!options.yes) {
220
+ if (!stdin.isTTY)
221
+ throw new KiokuFailure('不在终端里运行时要带 --yes 才写;先用 --dry-run 看计划')
222
+ if (!(await confirm(`写入这 ${todo.length} 条?[y/N] `, { stdin, out }))) {
223
+ out.write('没有写入\n')
224
+ return 0
225
+ }
226
+ }
227
+
228
+ let written = 0
229
+ const failed = []
230
+ // 连不上、超时这类不是某一条的问题:停下来,把已经写了多少、还剩多少说清楚,不让它跳出整个命令
231
+ let stopped = null
232
+ for (const [index, item] of todo.entries()) {
233
+ let result
234
+ try {
235
+ result = await write(config, item)
236
+ } catch (err) {
237
+ if (!(err instanceof KiokuFailure)) throw err
238
+ stopped = { reason: err.message, left: todo.length - index }
239
+ break
240
+ }
241
+ if (result.ok) written++
242
+ else failed.push({ item, ...result })
243
+ }
244
+ out.write(`\n写入 ${written} 条\n`)
245
+ for (const { item, reason, plaintext } of failed) {
246
+ out.write(`没有写入 ${item.uri}\n ← ${plain(item.source)}\n ${reason}\n`)
247
+ // 只说第几行、哪一类,不带值;行号按正文算(文件头之后)
248
+ for (const spot of plaintext ?? []) {
249
+ out.write(` 正文第 ${Number(spot.line) || '?'} 行:${plain(spot.kind)}\n`)
250
+ }
251
+ }
252
+ if (failed.some((entry) => entry.plaintext)) {
253
+ out.write('疑似明文凭据的没有写:把值存成凭据、正文里写占位符,或者从文件里去掉,再运行一次\n')
254
+ }
255
+ if (stopped) {
256
+ out.write(
257
+ `${stopped.reason}:还有 ${stopped.left} 条没有写,重新运行会接着写(已经写进去的会跳过)\n`,
258
+ )
259
+ }
260
+ out.write('本地的文件没有动。\n')
261
+ return stopped || failed.length || compared.some((item) => item.state === 'failed') ? 1 : 0
262
+ }
package/lib/kioku.mjs ADDED
@@ -0,0 +1,424 @@
1
+ // kioku 命令。kioku run 向 Kioku 取凭据的值,放进环境变量交给要跑的命令,命令的输出打过码再写出:
2
+ // 命令行、对话记录与发给模型的内容里只有变量名。
3
+ // 报错的文字都不带值和访问密钥:spawn 的参数错误会带出环境变量的值,fetch 的错误会带出请求头,
4
+ // 所以这两处只取错误类别
5
+
6
+ import { spawn } from 'node:child_process'
7
+ import { constants } from 'node:os'
8
+ import { isatty } from 'node:tty'
9
+
10
+ import { killTree, launch } from './command.mjs'
11
+ import { loadConfig } from './config.mjs'
12
+ import { IMPORT_USAGE, importMemories } from './import.mjs'
13
+ import { login, LOGIN_USAGE } from './login.mjs'
14
+ import { doctor, DOCTOR_USAGE } from './doctor.mjs'
15
+ import {
16
+ errorKind,
17
+ failureText,
18
+ fetchFailure,
19
+ isRedirect,
20
+ KiokuFailure,
21
+ redirectError,
22
+ } from './http.mjs'
23
+ import { setup, SETUP_USAGE } from './setup.mjs'
24
+ import { UsageError } from './usage.mjs'
25
+ import { createRedactor, MIN_REDACT_CHARS, redactable } from './redact.mjs'
26
+
27
+ // 等 Kioku 取值的上限(毫秒)
28
+ const TIMEOUT = 15_000
29
+ // 与服务端的上限一致
30
+ const MAX_REFS = 32
31
+ const MAX_PURPOSE = 200
32
+ const VARIABLE = /^[A-Za-z_][A-Za-z0-9_]*$/
33
+ const NAME = /^[a-z0-9][a-z0-9_-]{0,63}$/
34
+ const CONTROL = /\p{Cc}/u
35
+ // 不给命令留这两个变量,免得它把访问密钥或文件的位置顺手打印出来。这不是隔离:
36
+ // 访问密钥文件和命令属于同一个用户,命令照样读得到
37
+ const KEY_VARIABLES = ['KIOKU_API_KEY', 'KIOKU_API_KEY_FILE']
38
+ // 收到这些信号时转给命令。有终端时 SIGINT 除外:终端的 Ctrl-C 发给整个前台进程组,命令和 kioku 在同一个组里,
39
+ // 已经收到了,再转一次就成了两次(有的工具连按两次会跳过清理);SIGINT 照样接住,kioku 才能等命令处理完。
40
+ // 没有终端时(例如 Claude Code 的 Bash 工具)SIGINT 是单独发给 kioku 的,照样转发。
41
+ // 发给整个进程组的 SIGTERM、SIGHUP(没有终端时还有 SIGINT),命令会收到两次,这是已知的限制
42
+ const SIGNALS = ['SIGINT', 'SIGTERM', 'SIGHUP']
43
+ // 标准输入、输出或错误有一个是终端,就当作在终端里运行。用 isatty 查文件描述符,不碰 process.stdin:
44
+ // 那会建出读标准输入的流
45
+ const FROM_TERMINAL = isatty(0) || isatty(1) || isatty(2)
46
+ // 不发给自己的信号,退回 128 + 信号编号:SIGUSR1 会打开 Node 的调试端口,SIGPIPE 被 Node 忽略;
47
+ // 其余的会让 Node 自己转储,崩溃报告也算到 kioku 头上
48
+ const NOT_RERAISED = new Set([
49
+ 'SIGUSR1',
50
+ 'SIGPIPE',
51
+ 'SIGSEGV',
52
+ 'SIGABRT',
53
+ 'SIGBUS',
54
+ 'SIGILL',
55
+ 'SIGFPE',
56
+ 'SIGQUIT',
57
+ 'SIGTRAP',
58
+ 'SIGSYS',
59
+ 'SIGXCPU',
60
+ 'SIGXFSZ',
61
+ ])
62
+
63
+ export const USAGE = `用法:kioku run -e 变量=<标识>#<字段> [-e …] [--purpose <用途>] -- <命令> [参数…]
64
+
65
+ 向 Kioku 取凭据的值,放进环境变量交给命令;命令行和对话记录里只有变量名。
66
+ 命令输出里原样出现的值换成 ***(少于 ${MIN_REDACT_CHARS} 个字符的值除外)。
67
+ 打码只防值顺手出现在输出里,不是安全边界。
68
+
69
+ -e 变量=<标识>#<字段> 凭据 <标识> 的 <字段> 放进这个环境变量,可以写多个
70
+ --purpose <用途> 这次取用的用途,记进访问记录,最多 ${MAX_PURPOSE} 个字;用途里有空格时要加引号
71
+ -h, --help 显示本说明
72
+
73
+ 命令不经过 shell 直接执行。参数里写的 $变量 会被外层的 shell 提前展开成空值;
74
+ 要在参数里用变量,或者要用管道、重定向时,写成 sh -c '…',整段用单引号,变量放在双引号里:
75
+
76
+ kioku run -e PGPASSWORD=pg-main#password -- psql -h db.example.com -U app
77
+ kioku run -e TOKEN=github#token --purpose '查看 issue' -- sh -c 'curl -H "Authorization: Bearer $TOKEN" https://api.example.com/issues'
78
+
79
+ 退出码与命令相同,命令被信号结束时 kioku 也以同一个信号结束;参数不对、取值失败时为 2。
80
+ 地址与访问密钥:Claude Code 插件在会话开始时配好;在别处用时设置 KIOKU_SERVER_URL 与 KIOKU_API_KEY。
81
+ `
82
+
83
+ export { UsageError }
84
+
85
+ // 解析 kioku run 的参数。要看说明时返回 { help: true };否则返回 refs(要取的标识与字段,同一对只取一次)、
86
+ // variables([变量名, 值在 refs 里的下标])、purpose、command 与 args
87
+ export function parseRunArgs(argv) {
88
+ const refs = []
89
+ const refIndex = new Map()
90
+ const variables = new Map()
91
+ let purpose
92
+ let purposeGiven = false
93
+ let i = 0
94
+ for (; i < argv.length && argv[i] !== '--'; i++) {
95
+ const arg = argv[i]
96
+ if (arg === '-h' || arg === '--help') return { help: true }
97
+ if (arg === '-e') {
98
+ if (++i >= argv.length) throw new UsageError('-e 后面要写 变量=<标识>#<字段>')
99
+ const { name, identifier, field } = parseVariable(argv[i])
100
+ if (variables.has(name)) throw new UsageError(`变量 ${name} 写了两次`)
101
+ const ref = `${identifier}#${field}`
102
+ if (!refIndex.has(ref)) {
103
+ refIndex.set(ref, refs.length)
104
+ refs.push({ identifier, field })
105
+ }
106
+ variables.set(name, refIndex.get(ref))
107
+ } else if (arg === '--purpose' || arg.startsWith('--purpose=')) {
108
+ if (purposeGiven) throw new UsageError('--purpose 只能写一次')
109
+ purposeGiven = true
110
+ if (arg === '--purpose' && ++i >= argv.length) throw new UsageError('--purpose 后面要写用途')
111
+ purpose = parsePurpose(arg === '--purpose' ? argv[i] : arg.slice('--purpose='.length))
112
+ } else {
113
+ throw new UsageError(arg.startsWith('-') ? `不认识的参数 ${arg}` : '命令前面要写 --')
114
+ }
115
+ }
116
+ if (i >= argv.length) throw new UsageError('命令前面要写 --')
117
+ const command = argv[i + 1]
118
+ if (!command) throw new UsageError('-- 后面要写命令')
119
+ if (variables.size === 0) throw new UsageError('至少要写一个 -e')
120
+ if (refs.length > MAX_REFS) throw new UsageError(`一次最多取 ${MAX_REFS} 个字段`)
121
+ return { refs, variables: [...variables], purpose, command, args: argv.slice(i + 2) }
122
+ }
123
+
124
+ // 等号后面写错时只说格式,不复述写的内容:那里可能误填了值本身
125
+ function parseVariable(spec) {
126
+ const eq = spec.indexOf('=')
127
+ if (eq <= 0) throw new UsageError('-e 要写成 变量=<标识>#<字段>')
128
+ const name = spec.slice(0, eq)
129
+ if (!VARIABLE.test(name)) {
130
+ throw new UsageError(`变量名 ${name} 只能用字母、数字和下划线,不能以数字开头`)
131
+ }
132
+ const [identifier, field, ...rest] = spec.slice(eq + 1).split('#')
133
+ if (rest.length > 0 || !NAME.test(identifier) || !NAME.test(field ?? '')) {
134
+ throw new UsageError(
135
+ `${name} 要写成 ${name}=<标识>#<字段>;标识与字段名只用小写字母、数字、_ 和 -,以字母或数字开头,最长 64 个字符`,
136
+ )
137
+ }
138
+ return { name, identifier, field }
139
+ }
140
+
141
+ // 与服务端的规则一致:去掉首尾空白后不超过上限,不含控制字符,只有空白的当作没写
142
+ function parsePurpose(value) {
143
+ const text = value.trim()
144
+ if (text.length > MAX_PURPOSE) throw new UsageError(`--purpose 最多 ${MAX_PURPOSE} 个字`)
145
+ if (CONTROL.test(text)) throw new UsageError('--purpose 不能有换行等控制字符')
146
+ return text || undefined
147
+ }
148
+
149
+ // 服务端的错误文字原样给出,只去掉控制字符;万一带着访问密钥也盖掉
150
+ function serverError(data, status, key) {
151
+ const text = typeof data?.error === 'string' ? data.error : ''
152
+ const clean = text
153
+ .split(key)
154
+ .join('***')
155
+ .replace(/\p{Cc}+/gu, ' ')
156
+ .trim()
157
+ return clean || `Kioku 返回 HTTP ${status}`
158
+ }
159
+
160
+ // 已到期的凭据:服务端照常给值,在 expired 里列出标识与到期时间。旧的服务端没有这一项,按没有处理;
161
+ // 格式不对的项跳过,不因为提示让整次失败。打印之前去掉控制字符
162
+ function expiredOf(data) {
163
+ if (!Array.isArray(data?.expired)) return []
164
+ const clean = (text) => text.replace(/\p{Cc}+/gu, ' ').trim()
165
+ return data.expired.flatMap((item) =>
166
+ typeof item?.identifier === 'string' && typeof item.expiresAt === 'string'
167
+ ? [{ identifier: clean(item.identifier), expiresAt: clean(item.expiresAt) }]
168
+ : [],
169
+ )
170
+ }
171
+
172
+ // 按 refs 的顺序取出响应里的值;对不上时为 null
173
+ function valuesOf(data, refs) {
174
+ if (!Array.isArray(data?.values) || data.values.length !== refs.length) return null
175
+ const byRef = new Map()
176
+ for (const item of data.values) {
177
+ if (typeof item?.identifier !== 'string' || typeof item.field !== 'string') return null
178
+ if (typeof item.value !== 'string') return null
179
+ byRef.set(`${item.identifier}#${item.field}`, item.value)
180
+ }
181
+ const values = refs.map((r) => byRef.get(`${r.identifier}#${r.field}`))
182
+ return values.every((v) => v !== undefined) ? values : null
183
+ }
184
+
185
+ // 一次请求取全部值:任何一项取不到时整次失败,响应里不带值。连同已到期的凭据一起返回
186
+ async function resolveValues({ url, key }, refs, purpose) {
187
+ let res
188
+ let text
189
+ try {
190
+ res = await fetch(`${url}/v1/credentials/resolve`, {
191
+ method: 'POST',
192
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
193
+ body: JSON.stringify(purpose === undefined ? { refs } : { refs, purpose }),
194
+ // 不跟着跳转走:访问密钥只发给配置的地址
195
+ redirect: 'manual',
196
+ signal: AbortSignal.timeout(TIMEOUT),
197
+ })
198
+ text = await res.text()
199
+ } catch (err) {
200
+ throw new KiokuFailure(fetchFailure(err, TIMEOUT))
201
+ }
202
+ if (isRedirect(res.status)) {
203
+ throw new KiokuFailure(redirectError(res.status, res.headers.get('location'), url))
204
+ }
205
+ let data
206
+ try {
207
+ data = JSON.parse(text)
208
+ } catch {
209
+ // 不是 JSON 时按没有错误文字处理
210
+ }
211
+ if (!res.ok) throw new KiokuFailure(serverError(data, res.status, key))
212
+ const values = valuesOf(data, refs)
213
+ if (!values) throw new KiokuFailure('Kioku 的响应格式不对')
214
+ return { values, expired: expiredOf(data) }
215
+ }
216
+
217
+ // 子进程的一路输出打过码写到本进程对应的输出,全部写出之后 resolve
218
+ function relay(source, target, values) {
219
+ const redactor = createRedactor(values)
220
+ source.pipe(redactor)
221
+ redactor.pipe(target, { end: false })
222
+ // 子进程这一路出错或没有正常结束就关了,也把留着的尾巴冲刷出去
223
+ const finish = () => {
224
+ if (!redactor.writableEnded) redactor.end()
225
+ }
226
+ source.once('error', finish)
227
+ source.once('close', finish)
228
+ target.on('error', () => {
229
+ // 下游已经关了(例如后面接着 head):关掉给命令的这一路输出,等命令自己结束,退出码按命令的结果。
230
+ // 命令再写就会出错:Node 给子进程的输出是 UNIX 套接字对,macOS 上命令收到 SIGPIPE;Linux 上关的时候
231
+ // 还有没读完的数据,连接被重置,命令拿到的是 ECONNRESET,收不到 SIGPIPE,多半自己报错退出
232
+ redactor.unpipe(target)
233
+ redactor.resume()
234
+ source.destroy()
235
+ })
236
+ return new Promise((resolve) => redactor.once('end', resolve))
237
+ }
238
+
239
+ // 本进程的标准输出与标准错误都写完:之前写进去的都交给系统之后才回调。自己以信号结束之前要等这一步,
240
+ // 否则还排着队的输出就丢了
241
+ function flushed() {
242
+ const flush = (stream) => new Promise((resolve) => stream.write('', () => resolve()))
243
+ return Promise.all([flush(process.stdout), flush(process.stderr)])
244
+ }
245
+
246
+ // 以这个信号结束本进程:外层的 shell 据此决定要不要停下。例如循环里按了 Ctrl-C,
247
+ // kioku 按 128 + n 正常退出的话,shell 当作命令自己处理了 SIGINT,循环会接着跑。
248
+ // 发不出、或者发了进程还在的,退回 128 + 信号编号作为退出码
249
+ function exitBySignal(signal) {
250
+ if (!NOT_RERAISED.has(signal)) {
251
+ try {
252
+ process.kill(process.pid, signal)
253
+ } catch {
254
+ // 认不出的信号名
255
+ }
256
+ }
257
+ return 128 + (constants.signals[signal] ?? 0)
258
+ }
259
+
260
+ // 启动命令,等它结束、输出写完,返回退出码;命令被信号结束时本进程以同一个信号结束
261
+ function runCommand(command, args, env, values) {
262
+ return new Promise((resolve) => {
263
+ let child
264
+ let run
265
+ try {
266
+ // Windows 上 npm、pnpm 这类命令是 .cmd,要经 cmd.exe 起(launch 算好怎么起)
267
+ run = launch(command, args, env)
268
+ if (!run) {
269
+ process.stderr.write(`kioku:找不到命令 ${command}\n`)
270
+ resolve(127)
271
+ return
272
+ }
273
+ // 不用 detached:命令留在 kioku 的进程组里,整组被结束时它不会变成带着值的孤儿进程
274
+ child = spawn(run.file, run.args, {
275
+ env,
276
+ stdio: ['inherit', 'pipe', 'pipe'],
277
+ ...run.options,
278
+ })
279
+ } catch (err) {
280
+ process.stderr.write(`kioku:无法启动 ${command}(${failureText(err)})\n`)
281
+ resolve(126)
282
+ return
283
+ }
284
+ let failure
285
+ child.once('error', (err) => {
286
+ failure = err
287
+ })
288
+ // 命令结束之后、输出写完之前收到的信号:等输出写完,kioku 以它结束
289
+ let late
290
+ const stopListening = () => {
291
+ for (const signal of SIGNALS) process.off(signal, onSignal)
292
+ }
293
+ const onSignal = (signal) => {
294
+ if (child.exitCode === null && child.signalCode === null) {
295
+ // 隔着 cmd.exe 时连它下面真正的命令一起结束,不留一个带着值的进程
296
+ if (signal !== 'SIGINT' || !FROM_TERMINAL) killTree(child, signal, { shell: run.shell })
297
+ return
298
+ }
299
+ if (late === undefined) {
300
+ // 命令已经结束、输出还没写完:交给下面 close 的处理,写完再结束
301
+ late = signal
302
+ return
303
+ }
304
+ // 又收到一次:不再等(例如命令留下的后台进程一直占着输出),立刻以这个信号结束
305
+ stopListening()
306
+ process.kill(process.pid, signal)
307
+ }
308
+ for (const signal of SIGNALS) process.on(signal, onSignal)
309
+ const outputs = [
310
+ relay(child.stdout, process.stdout, values),
311
+ relay(child.stderr, process.stderr, values),
312
+ ]
313
+ child.once('close', async (code, signal) => {
314
+ await Promise.all(outputs)
315
+ if (child.pid === undefined) {
316
+ stopListening()
317
+ // 没能启动:和 shell 一样,找不到命令为 127,别的为 126
318
+ const notFound = failure?.code === 'ENOENT'
319
+ process.stderr.write(
320
+ notFound
321
+ ? `kioku:找不到命令 ${command}\n`
322
+ : `kioku:无法启动 ${command}(${errorKind(failure)})\n`,
323
+ )
324
+ resolve(notFound ? 127 : 126)
325
+ return
326
+ }
327
+ // 正常退出也先等输出写完、再去掉信号的处理:这期间收到的信号同样等写完再结束,
328
+ // 否则 Node 还在往外写的时候被信号结束,排着队的输出就丢了
329
+ await flushed()
330
+ const ending = signal ?? late
331
+ stopListening()
332
+ resolve(ending ? exitBySignal(ending) : (code ?? 1))
333
+ })
334
+ })
335
+ }
336
+
337
+ async function run(argv) {
338
+ let options
339
+ try {
340
+ options = parseRunArgs(argv)
341
+ } catch (err) {
342
+ if (!(err instanceof UsageError)) throw err
343
+ process.stderr.write(`kioku:${err.message}\n\n${USAGE}`)
344
+ return 2
345
+ }
346
+ if (options.help) {
347
+ process.stdout.write(USAGE)
348
+ return 0
349
+ }
350
+ const { refs, variables, purpose, command, args } = options
351
+ let resolved
352
+ try {
353
+ resolved = await resolveValues(await loadConfig(process.env), refs, purpose)
354
+ } catch (err) {
355
+ if (!(err instanceof KiokuFailure)) throw err
356
+ process.stderr.write(`kioku:${err.message}\n`)
357
+ return 2
358
+ }
359
+ const { values, expired } = resolved
360
+ const withNul = refs.findIndex((_, i) => values[i].includes('\0'))
361
+ if (withNul !== -1) {
362
+ const { identifier, field } = refs[withNul]
363
+ process.stderr.write(`kioku:${identifier}#${field} 的值含有空字符,放不进环境变量\n`)
364
+ return 2
365
+ }
366
+ const env = { ...process.env }
367
+ for (const name of KEY_VARIABLES) delete env[name]
368
+ for (const [name, index] of variables) env[name] = values[index]
369
+ const short = variables.filter(([, index]) => !redactable(values[index])).map(([name]) => name)
370
+ if (short.length > 0) process.stderr.write(`kioku:${short.join('、')} 的值太短,输出里不打码\n`)
371
+ // 已到期的照常交给命令,提示一句:值可能已失效,命令失败时先想到它
372
+ for (const { identifier, expiresAt } of expired) {
373
+ process.stderr.write(`kioku:凭据 ${identifier} 已于 ${expiresAt} 到期,值可能已失效\n`)
374
+ }
375
+ return runCommand(command, args, env, values)
376
+ }
377
+
378
+ // 入口:返回退出码
379
+ const OVERVIEW = `用法:kioku <子命令> [参数…]
380
+
381
+ run 向 Kioku 取凭据的值,放进环境变量交给命令
382
+ login 用浏览器授权签发访问密钥并配好这个平台
383
+ setup 停用平台自带的长期记忆,由 Kioku 接管
384
+ doctor 检查地址、访问密钥与平台的配置
385
+ import 把平台自带的本地长期记忆迁进 Kioku
386
+
387
+ 各子命令的说明:kioku <子命令> --help
388
+ `
389
+
390
+ // 说明类的子命令:参数写错时打印原因与说明,以 2 退出;别的失败原因写到标准错误
391
+ async function guarded(name, usage, fn, argv) {
392
+ if (argv.includes('-h') || argv.includes('--help')) {
393
+ process.stdout.write(usage)
394
+ return 0
395
+ }
396
+ try {
397
+ return await fn(argv)
398
+ } catch (err) {
399
+ if (err instanceof UsageError) {
400
+ process.stderr.write(`kioku ${name}:${err.message}\n\n${usage}`)
401
+ return 2
402
+ }
403
+ if (err instanceof KiokuFailure) {
404
+ process.stderr.write(`kioku ${name}:${err.message}\n`)
405
+ return 2
406
+ }
407
+ throw err
408
+ }
409
+ }
410
+
411
+ export async function main(argv) {
412
+ const [sub, ...rest] = argv
413
+ if (sub === '-h' || sub === '--help') {
414
+ process.stdout.write(OVERVIEW)
415
+ return 0
416
+ }
417
+ if (sub === 'run') return run(rest)
418
+ if (sub === 'login') return guarded('login', LOGIN_USAGE, login, rest)
419
+ if (sub === 'setup') return guarded('setup', SETUP_USAGE, setup, rest)
420
+ if (sub === 'doctor') return guarded('doctor', DOCTOR_USAGE, doctor, rest)
421
+ if (sub === 'import') return guarded('import', IMPORT_USAGE, importMemories, rest)
422
+ process.stderr.write(sub === undefined ? OVERVIEW : `kioku:不认识的子命令 ${sub}\n\n${OVERVIEW}`)
423
+ return 2
424
+ }