@kioku-memory/plugin-opencode 0.0.0-stage → 0.4.1

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.
@@ -0,0 +1,152 @@
1
+ // 起 npm 装的那类外部命令(openclaw、hermes,以及 kioku run 要跑的命令)。
2
+ // Windows 上这类命令是 .cmd 文件,不经 cmd.exe 起不来(直接起会报找不到,或者被 Node 拒绝),
3
+ // 而经 cmd.exe 时参数要按它的规则转义,否则参数里的 & | % 这类字符会被当成命令。
4
+ // 别的系统上什么都不做,原样交给系统:找命令、判断能不能执行都是系统的事。
5
+ // 转义的规则照 cross-spawn 的做法写(MIT,来源登记在 NOTICE)
6
+
7
+ import { execFile, spawn } from 'node:child_process'
8
+ import { accessSync, constants, statSync } from 'node:fs'
9
+ import { join, win32 } from 'node:path'
10
+
11
+ import { KiokuFailure } from './http.mjs'
12
+
13
+ const isFile = (file) => {
14
+ try {
15
+ return statSync(file).isFile()
16
+ } catch {
17
+ return false
18
+ }
19
+ }
20
+
21
+ // Windows 的环境变量名不分大小写。同一个名字写了几种大小写时(Path 与 PATH),
22
+ // 取排序后的第一个:Node 把环境交给子进程时也是这样取的,两边看到的要是同一个
23
+ export function envValue(env, name) {
24
+ const key = Object.keys(env)
25
+ .filter((item) => item.toLowerCase() === name.toLowerCase())
26
+ .sort()[0]
27
+ return key === undefined ? undefined : env[key]
28
+ }
29
+
30
+ // Windows 上一个命令的完整路径;找不到为 null。名字里带目录时只看这个位置,否则在 PATH 里逐个目录找。
31
+ // 名字没写扩展名时只按 PATHEXT 补上扩展名找,不找原样的名字:npm 在 .cmd 旁边还放着一个同名、
32
+ // 没有扩展名的脚本(给 sh 用的),Windows 起不了它
33
+ export function findCommand(name, env, { exists = isFile } = {}) {
34
+ if (typeof name !== 'string' || !name) return null
35
+ const extensions = (envValue(env, 'PATHEXT') || '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean)
36
+ const suffixes = win32.extname(name) ? ['', ...extensions] : extensions
37
+ const dirs = /[\\/]/.test(name)
38
+ ? ['']
39
+ : (envValue(env, 'PATH') ?? '')
40
+ .split(win32.delimiter)
41
+ // 带空格的目录有人会加上引号
42
+ .map((dir) => dir.replace(/^"(.*)"$/, '$1'))
43
+ .filter(Boolean)
44
+ for (const dir of dirs) {
45
+ for (const suffix of suffixes) {
46
+ const file = (dir ? win32.join(dir, name) : name) + suffix
47
+ if (exists(file)) return file
48
+ }
49
+ }
50
+ return null
51
+ }
52
+
53
+ // PATH 里有没有这个命令(向导的面板用来看平台装没装)。Windows 上照 findCommand 的规则找;
54
+ // 别的系统上找能执行的普通文件
55
+ export function hasCommand(name, env, { platform = process.platform } = {}) {
56
+ if (platform === 'win32') return findCommand(name, env) !== null
57
+ if (typeof name !== 'string' || !name) return false
58
+ const dirs = /\//.test(name) ? [''] : (envValue(env, 'PATH') ?? '').split(':').filter(Boolean)
59
+ return dirs.some((dir) => {
60
+ const file = dir ? join(dir, name) : name
61
+ try {
62
+ accessSync(file, constants.X_OK)
63
+ return statSync(file).isFile()
64
+ } catch {
65
+ return false
66
+ }
67
+ })
68
+ }
69
+
70
+ // cmd.exe 认作有特殊含义的字符
71
+ const META = /([()\][%!^"`<>&|;, *?])/g
72
+
73
+ // 一个参数在 cmd.exe 的命令行里的写法:先按 Windows 程序解析参数的规则加引号、处理反斜杠与引号,
74
+ // 再给 cmd.exe 自己的特殊字符加 ^。经 node_modules/.bin 里的 .cmd 转一道的要转义两遍(它里面又解析一次)
75
+ function escapeArgument(value, twice) {
76
+ let arg = String(value)
77
+ arg = arg.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"')
78
+ arg = arg.replace(/(?=(\\+?)?)\1$/, '$1$1')
79
+ arg = `"${arg}"`.replace(META, '^$1')
80
+ return twice ? arg.replace(META, '^$1') : arg
81
+ }
82
+
83
+ // 怎么起这个命令:{ file, args, options, shell },交给 spawn、execFile;Windows 上找不到这个命令时为 null。
84
+ // shell 为真表示中间隔着一层 cmd.exe,结束它要用 killTree。别的系统上原样返回,找不到由系统报 ENOENT
85
+ export function launch(name, args, env, { platform = process.platform, exists } = {}) {
86
+ if (platform !== 'win32') return { file: name, args, options: {}, shell: false }
87
+ const file = findCommand(name, env, { exists })
88
+ if (!file) return null
89
+ if (!/\.(cmd|bat)$/i.test(file)) return { file, args, options: {}, shell: false }
90
+ // cmd.exe 把换行当成一行命令的结尾,后面的参数会悄悄丢掉:不起
91
+ if ([file, ...args].some((item) => /[\r\n]/.test(String(item)))) {
92
+ throw new KiokuFailure('参数里有换行,经 cmd.exe 起的命令收不到完整的参数')
93
+ }
94
+ const twice = /node_modules[\\/]\.bin[\\/][^\\/]+\.cmd$/i.test(file)
95
+ const line = [file.replace(META, '^$1'), ...args.map((arg) => escapeArgument(arg, twice))]
96
+ return {
97
+ file: envValue(env, 'ComSpec') || 'cmd.exe',
98
+ // /d 不跑注册表里的自动命令,/s 加外层引号让整行原样交给 /c
99
+ args: ['/d', '/s', '/c', `"${line.join(' ')}"`],
100
+ // 这一行已经按 cmd.exe 的规则写好了,不让 Node 再加一层引号
101
+ options: { windowsVerbatimArguments: true },
102
+ shell: true,
103
+ }
104
+ }
105
+
106
+ // 结束一个起好的命令。隔着 cmd.exe 时只结束它的话,真正的命令还活着、还占着输出的管道,
107
+ // 所以连它下面的进程一起结束(Windows 上没有信号可转,只能强行结束)
108
+ export function killTree(child, signal, { shell, platform = process.platform } = {}) {
109
+ if (platform !== 'win32' || !shell || child.pid === undefined) return child.kill(signal)
110
+ try {
111
+ spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' }).on(
112
+ 'error',
113
+ () => child.kill(),
114
+ )
115
+ return true
116
+ } catch {
117
+ return child.kill()
118
+ }
119
+ }
120
+
121
+ // 跑一个命令到结束,收下它的输出:{ found: false }(没有这个命令),
122
+ // 或者 { found: true, ok, stdout, output }(output 是两路输出合在一起,只用来认是哪种失败)。
123
+ // 超过时限就结束它(连同它下面的进程),算失败。不抛错
124
+ export function capture(name, args, env, { timeout, maxBuffer = 8 * 1024 * 1024 } = {}) {
125
+ let run
126
+ try {
127
+ run = launch(name, args, env)
128
+ } catch {
129
+ return Promise.resolve({ found: true, ok: false, stdout: '', output: '' })
130
+ }
131
+ if (!run) return Promise.resolve({ found: false })
132
+ return new Promise((resolve) => {
133
+ let timer
134
+ const child = execFile(
135
+ run.file,
136
+ run.args,
137
+ { env, maxBuffer, ...run.options },
138
+ (err, stdout, stderr) => {
139
+ clearTimeout(timer)
140
+ if (err?.code === 'ENOENT') resolve({ found: false })
141
+ else {
142
+ const out = String(stdout ?? '')
143
+ resolve({ found: true, ok: !err, stdout: out, output: `${out}\n${stderr ?? ''}` })
144
+ }
145
+ },
146
+ )
147
+ if (timeout) {
148
+ timer = setTimeout(() => killTree(child, 'SIGTERM', { shell: run.shell }), timeout)
149
+ timer.unref?.()
150
+ }
151
+ })
152
+ }
package/lib/config.mjs ADDED
@@ -0,0 +1,50 @@
1
+ // kioku 命令的地址与访问密钥:从环境变量与访问密钥文件读
2
+
3
+ import { readFile, utimes } from 'node:fs/promises'
4
+
5
+ import { errorKind, keyFormatError, KiokuFailure } from './http.mjs'
6
+
7
+ const NOT_CONFIGURED =
8
+ '缺少 Kioku 的地址或访问密钥:在 Claude Code 里启用 kioku 插件、填好配置后新开会话,或者设置 KIOKU_SERVER_URL 与 KIOKU_API_KEY'
9
+
10
+ // 地址或访问密钥根本没有配(区别于配了但不对)
11
+ export class NotConfigured extends KiokuFailure {}
12
+
13
+ // 地址与访问密钥。访问密钥先读插件在会话开始时配好的 KIOKU_API_KEY_FILE,读不到再用 KIOKU_API_KEY;
14
+ // 两样都没有才报错,报错只写文件的位置与错误类别
15
+ export async function loadConfig(env) {
16
+ const url = (env.KIOKU_SERVER_URL ?? '').trim().replace(/\/+$/, '')
17
+ const file = env.KIOKU_API_KEY_FILE
18
+ let key = ''
19
+ let fileProblem
20
+ if (file) {
21
+ try {
22
+ key = (await readFile(file, 'utf8')).trim()
23
+ if (!key) fileProblem = '文件是空的'
24
+ } catch (err) {
25
+ fileProblem = errorKind(err)
26
+ }
27
+ // 用的时候更新修改时间:会话开始时会删掉很久没用过的访问密钥文件
28
+ if (key) await utimes(file, new Date(), new Date()).catch(() => {})
29
+ }
30
+ if (!key) key = (env.KIOKU_API_KEY ?? '').trim()
31
+ if (!url) throw new NotConfigured(NOT_CONFIGURED)
32
+ if (!key) {
33
+ if (!fileProblem) throw new NotConfigured(NOT_CONFIGURED)
34
+ throw new KiokuFailure(
35
+ `无法读取访问密钥文件 ${file}(${fileProblem}):新开会话,或者设置 KIOKU_API_KEY`,
36
+ )
37
+ }
38
+ let protocol
39
+ try {
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
+ }
47
+ const problem = keyFormatError(key)
48
+ if (problem) throw new KiokuFailure(problem)
49
+ return { url, key }
50
+ }
package/lib/http.mjs ADDED
@@ -0,0 +1,57 @@
1
+ // 钩子与 kioku 命令共用的访问密钥检查与报错。报错只给插件自己写的文字或错误类别:
2
+ // fetch 的报错会带上整个 Authorization 请求头,响应解析失败的文字会带上响应的开头
3
+
4
+ // 访问密钥只能是可见的 ASCII 字符:别的字符放不进请求头,fetch 报错时会把整个请求头写进错误文字
5
+ const KEY = /^[\x21-\x7e]+$/
6
+ // 错误码(ECONNREFUSED、UND_ERR_SOCKET 这类)与错误类名(TypeError 这类)的样子
7
+ const CODE = /^[A-Z][A-Z0-9_]*$/
8
+ const NAME = /^[A-Z][A-Za-z]*$/
9
+
10
+ // 文字由插件自己写、不含值和访问密钥的失败,可以原样打印
11
+ export class KiokuFailure extends Error {}
12
+
13
+ // 访问密钥的格式不对时返回原因,否则为 null
14
+ export function keyFormatError(key) {
15
+ return KEY.test(key) ? null : '访问密钥的格式不对:只能是可见的 ASCII 字符,不能有空白'
16
+ }
17
+
18
+ // 错误的类别:只取 code 或 name,不取文字
19
+ export function errorKind(err) {
20
+ if (typeof err?.code === 'string' && CODE.test(err.code)) return err.code
21
+ if (typeof err?.name === 'string' && NAME.test(err.name)) return err.name
22
+ return '未知错误'
23
+ }
24
+
25
+ // fetch 失败的原因:超时,或者连不上(附 cause 的错误码)
26
+ export function fetchFailure(err, timeoutMs) {
27
+ if (err?.name === 'TimeoutError' || err?.name === 'AbortError') {
28
+ return `连接 Kioku 超时(${timeoutMs / 1000} 秒)`
29
+ }
30
+ const code = err?.cause?.code
31
+ return typeof code === 'string' && CODE.test(code)
32
+ ? `无法连接 Kioku(${code})`
33
+ : '无法连接 Kioku'
34
+ }
35
+
36
+ // 收到跳转(3xx)时的报错:说明要把地址改成跳转之后的地址。请求都不跟着跳转走,访问密钥只发给配置的地址;
37
+ // 跳转目标只给协议与主机,路径与查询参数里可能带着令牌;跳到同一个主机、或者没给目标时不举例
38
+ export function redirectError(status, location, url) {
39
+ let origin
40
+ try {
41
+ const target = new URL(location ?? '', `${url}/`)
42
+ const web = target.protocol === 'https:' || target.protocol === 'http:'
43
+ if (web && target.origin !== new URL(url).origin) origin = target.origin
44
+ } catch {
45
+ // 跳转目标解析不了时不举例
46
+ }
47
+ return `Kioku 返回了跳转(${status}),把地址改成跳转之后的地址${origin ? `(例如 ${origin})` : ''}`
48
+ }
49
+
50
+ export function isRedirect(status) {
51
+ return status >= 300 && status < 400
52
+ }
53
+
54
+ // 要打印的失败原因:插件自己写的原样给出,别的只给类别
55
+ export function failureText(err) {
56
+ return err instanceof KiokuFailure ? err.message : errorKind(err)
57
+ }
package/lib/kioku.mjs ADDED
@@ -0,0 +1,53 @@
1
+ // 插件目录里放着的精简 kioku 入口:只实现 kioku run(插件启用期间放在 PATH 里给 Bash 工具用)。
2
+ // 向导、接入、检查、日常记忆读写等完整命令行在 npm 包 @kioku-memory/cli
3
+
4
+ import { parseRunArgs, run, USAGE, UsageError } from './run.mjs'
5
+
6
+ export { parseRunArgs, run, USAGE, UsageError }
7
+
8
+ const OVERVIEW = `用法:kioku run -e 变量=<标识>#<字段> [-e …] [--purpose <用途>] -- <命令> [参数…]
9
+
10
+ 插件目录内置的命令行入口仅包含 kioku run(向 Kioku 取凭据,放进环境变量并打码输出)。
11
+ 向导、接入管理与记忆读写等完整功能见 @kioku-memory/cli:
12
+
13
+ npx @kioku-memory/cli
14
+ npm install -g @kioku-memory/cli
15
+
16
+ 运行子命令用法:kioku run --help
17
+ `
18
+
19
+ const FULL_CLI_COMMANDS = new Set([
20
+ 'connect',
21
+ 'disconnect',
22
+ 'upgrade',
23
+ 'status',
24
+ 'login',
25
+ 'setup',
26
+ 'install',
27
+ 'doctor',
28
+ 'clean',
29
+ 'import',
30
+ 'local',
31
+ 'open',
32
+ 'search',
33
+ 'get',
34
+ 'ls',
35
+ 'add',
36
+ ])
37
+
38
+ export async function main(argv) {
39
+ const [sub, ...rest] = argv
40
+ if (sub === '-h' || sub === '--help') {
41
+ process.stdout.write(OVERVIEW)
42
+ return 0
43
+ }
44
+ if (sub === 'run') return run(rest)
45
+ if (sub && FULL_CLI_COMMANDS.has(sub)) {
46
+ process.stderr.write(
47
+ `kioku:插件内置入口仅含 run 子命令;运行 npx @kioku-memory/cli ${sub}(或全局安装 @kioku-memory/cli)\n`,
48
+ )
49
+ return 2
50
+ }
51
+ process.stderr.write(sub === undefined ? OVERVIEW : `kioku:不认识的子命令 ${sub}\n\n${OVERVIEW}`)
52
+ return 2
53
+ }
@@ -0,0 +1,128 @@
1
+ // 各平台的钩子共用的生命周期转发:把 session.start、prompt.submit、turn.end 交给 Kioku 的生命周期端点。
2
+ // 这里不放提示词和格式逻辑,都由服务端决定;怎么从平台取输入、怎么把结果交还平台,由各插件自己写。
3
+ // 报错和 kioku 命令一样不带访问密钥:格式不对的访问密钥不发出去,fetch 的报错只取类别,
4
+ // 也不跟着跳转走,访问密钥只发给配置的地址
5
+
6
+ import { execFile, execFileSync } from 'node:child_process'
7
+ import { basename } from 'node:path'
8
+
9
+ import { fetchFailure, isRedirect, keyFormatError, KiokuFailure, redirectError } from './http.mjs'
10
+
11
+ // 各事件等待服务端的上限(毫秒),要比平台给钩子的时限短
12
+ export const TIMEOUTS = { 'session.start': 8000, 'prompt.submit': 5000, 'turn.end': 5000 }
13
+ // 与服务端 contracts 的上限一致
14
+ export const MAX_PROMPT = 20_000
15
+ export const MAX_REPLY = 20_000
16
+ export const MAX_SESSION_ID = 200
17
+ const MAX_NAME = 128
18
+
19
+ // 配置写错了:访问密钥格式不对(kind 为 key),或者服务地址返回跳转(kind 为 url)。
20
+ // 和没有配置一样,平台可以在会话开始时提示一次;文字不带访问密钥
21
+ export class Misconfigured extends KiokuFailure {
22
+ constructor(message, kind) {
23
+ super(message)
24
+ this.kind = kind
25
+ }
26
+ }
27
+
28
+ // 服务地址去掉首尾空白与结尾的斜杠
29
+ export function normalizeBase(url) {
30
+ return (url ?? '').trim().replace(/\/+$/, '')
31
+ }
32
+
33
+ // 访问密钥的格式不对时抛 Misconfigured
34
+ export function assertKeyFormat(key) {
35
+ const problem = keyFormatError(key)
36
+ if (problem) throw new Misconfigured(problem, 'key')
37
+ }
38
+
39
+ // 按长度截断时不切开代理对(表情这类字符):落单的半个到了服务端会变成替换字符
40
+ export function clip(text, max) {
41
+ if (text.length <= max) return text
42
+ const code = text.charCodeAt(max - 1)
43
+ return text.slice(0, code >= 0xd800 && code <= 0xdbff ? max - 1 : max)
44
+ }
45
+
46
+ // 当前项目的目录名与 git 仓库名,服务端用它们召回与项目相关的记忆;取不到的就不带
47
+ export function projectOf(cwd) {
48
+ const project = {}
49
+ const dirName = basename(cwd)
50
+ if (dirName) project.dirName = dirName.slice(0, MAX_NAME)
51
+ try {
52
+ const remote = execFileSync('git', ['-C', cwd, 'remote', 'get-url', 'origin'], {
53
+ encoding: 'utf8',
54
+ timeout: 1500,
55
+ stdio: ['ignore', 'pipe', 'ignore'],
56
+ }).trim()
57
+ const repoName = /([^/:]+?)(?:\.git)?$/.exec(remote)?.[1]
58
+ if (repoName) project.repoName = repoName.slice(0, MAX_NAME)
59
+ } catch {
60
+ // 不是 git 仓库或没有 origin
61
+ }
62
+ return project
63
+ }
64
+
65
+ // 同上,不堵住事件循环:给在宿主进程里跑的扩展用(同步的那个会让宿主的界面停住)
66
+ export function projectOfAsync(cwd) {
67
+ const project = {}
68
+ const dirName = basename(cwd)
69
+ if (dirName) project.dirName = dirName.slice(0, MAX_NAME)
70
+ return new Promise((resolve) => {
71
+ execFile(
72
+ 'git',
73
+ ['-C', cwd, 'remote', 'get-url', 'origin'],
74
+ { encoding: 'utf8', timeout: 1500 },
75
+ (err, stdout) => {
76
+ const repoName = err ? undefined : /([^/:]+?)(?:\.git)?$/.exec(stdout.trim())?.[1]
77
+ if (repoName) project.repoName = repoName.slice(0, MAX_NAME)
78
+ resolve(project)
79
+ },
80
+ )
81
+ })
82
+ }
83
+
84
+ // 服务端要注入的上下文文本;没有时为 undefined。只取文本,输出里的其他字段一律不用:
85
+ // 记忆服务能决定注入什么内容,但不能挡住用户的输入或改变会话
86
+ export function contextOf(hostOutput) {
87
+ if (hostOutput?.mode === 'stdout_json') {
88
+ return (
89
+ hostOutput.value?.hookSpecificOutput?.additionalContext ??
90
+ hostOutput.value?.injectSteps?.[0]?.systemMessage?.systemMessage
91
+ )
92
+ }
93
+ if (hostOutput?.mode === 'stdout_text') return hostOutput.value
94
+ // 没有专门输出格式的运行时:服务端直接给文本
95
+ if (hostOutput?.mode === 'return_value') {
96
+ return (
97
+ hostOutput.value?.systemContext ??
98
+ hostOutput.value?.promptContext ??
99
+ hostOutput.value?.context
100
+ )
101
+ }
102
+ return undefined
103
+ }
104
+
105
+ // 把一个生命周期事件交给服务端;连不上、超时、取消、跳转与非 2xx 都以 KiokuFailure 抛出
106
+ export async function postEvent(base, key, body, timeout, signal) {
107
+ let res
108
+ try {
109
+ res = await fetch(`${base}/v1/lifecycle/event`, {
110
+ method: 'POST',
111
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
112
+ body: JSON.stringify(body),
113
+ redirect: 'manual',
114
+ // 宿主给了中止信号时(用户取消了这次输入)一起听
115
+ signal: signal
116
+ ? AbortSignal.any([AbortSignal.timeout(timeout), signal])
117
+ : AbortSignal.timeout(timeout),
118
+ })
119
+ } catch (err) {
120
+ if (signal?.aborted) throw new KiokuFailure('已取消')
121
+ throw new KiokuFailure(fetchFailure(err, timeout))
122
+ }
123
+ if (isRedirect(res.status)) {
124
+ throw new Misconfigured(redirectError(res.status, res.headers.get('location'), base), 'url')
125
+ }
126
+ if (!res.ok) throw new KiokuFailure(`HTTP ${res.status}`)
127
+ return res
128
+ }
package/lib/mcp.mjs ADDED
@@ -0,0 +1,142 @@
1
+ // 向 Kioku 的 MCP 端点发一次调用(取工具清单、调用工具)。给没有自己的 MCP 客户端、
2
+ // 要把 Kioku 的工具登记成平台自己的工具的平台用。端点是无状态的,一次请求一个回答,不用先握手
3
+
4
+ import { randomUUID } from 'node:crypto'
5
+ import { readFileSync } from 'node:fs'
6
+ import { chmod, mkdir, rename, rm, writeFile } from 'node:fs/promises'
7
+
8
+ import { fetchFailure, isRedirect, KiokuFailure, redirectError } from './http.mjs'
9
+ import { profileDir, profileFile } from './profile.mjs'
10
+ import { plain } from './text.mjs'
11
+
12
+ export const TOOLS_TIMEOUT = 8000
13
+ export const TOOL_CALL_TIMEOUT = 30_000
14
+
15
+ // 回答可能是一段事件流:取最后一条 data
16
+ function payloadOf(text, contentType) {
17
+ if (!contentType.includes('text/event-stream')) return text
18
+ const data = text
19
+ .split(/\r?\n/)
20
+ .filter((line) => line.startsWith('data:'))
21
+ .map((line) => line.slice(5).trim())
22
+ return data.at(-1) ?? ''
23
+ }
24
+
25
+ // 一次 JSON-RPC 调用,返回 result。连不上、超时、取消、跳转、访问密钥无效、响应不对、服务端报错都以 KiokuFailure 抛出
26
+ export async function mcpCall({ url, key }, method, params, timeout, signal) {
27
+ let res
28
+ let text
29
+ try {
30
+ res = await fetch(`${url}/v1/mcp`, {
31
+ method: 'POST',
32
+ headers: {
33
+ 'content-type': 'application/json',
34
+ accept: 'application/json, text/event-stream',
35
+ authorization: `Bearer ${key}`,
36
+ },
37
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
38
+ // 不跟着跳转走:访问密钥只发给配置的地址
39
+ redirect: 'manual',
40
+ signal: signal
41
+ ? AbortSignal.any([AbortSignal.timeout(timeout), signal])
42
+ : AbortSignal.timeout(timeout),
43
+ })
44
+ text = await res.text()
45
+ } catch (err) {
46
+ if (signal?.aborted) throw new KiokuFailure('已取消')
47
+ throw new KiokuFailure(fetchFailure(err, timeout))
48
+ }
49
+ if (isRedirect(res.status)) {
50
+ throw new KiokuFailure(redirectError(res.status, res.headers.get('location'), url))
51
+ }
52
+ if (res.status === 401) throw new KiokuFailure('访问密钥无效或已吊销')
53
+ if (!res.ok) throw new KiokuFailure(`Kioku 返回 HTTP ${res.status}`)
54
+ let data
55
+ try {
56
+ data = JSON.parse(payloadOf(text, res.headers.get('content-type') ?? ''))
57
+ } catch {
58
+ data = null
59
+ }
60
+ if (data === null || typeof data !== 'object') throw new KiokuFailure('Kioku 的响应格式不对')
61
+ if (data.error) {
62
+ // 服务端写的原因压成一行再给
63
+ const reason = plain(data.error.message)
64
+ throw new KiokuFailure(reason ? `Kioku 没有接受这次调用:${reason}` : 'Kioku 没有接受这次调用')
65
+ }
66
+ return data.result
67
+ }
68
+
69
+ // 清单里能用的工具:名字、说明、参数的 schema 都在的
70
+ export function toolsOf(result) {
71
+ const tools = Array.isArray(result?.tools) ? result.tools : []
72
+ return tools
73
+ .filter(
74
+ (tool) =>
75
+ typeof tool?.name === 'string' &&
76
+ tool.name &&
77
+ typeof tool.description === 'string' &&
78
+ tool.inputSchema !== null &&
79
+ typeof tool.inputSchema === 'object' &&
80
+ !Array.isArray(tool.inputSchema),
81
+ )
82
+ .map(({ name, description, inputSchema }) => ({ name, description, inputSchema }))
83
+ }
84
+
85
+ export async function listTools(target, signal) {
86
+ return toolsOf(await mcpCall(target, 'tools/list', {}, TOOLS_TIMEOUT, signal))
87
+ }
88
+
89
+ // 调用一个工具,返回 { text, isError }:结果里的文字块连成一段
90
+ export async function callTool(target, name, args, signal) {
91
+ const result = await mcpCall(
92
+ target,
93
+ 'tools/call',
94
+ { name, arguments: args ?? {} },
95
+ TOOL_CALL_TIMEOUT,
96
+ signal,
97
+ )
98
+ const blocks = Array.isArray(result?.content) ? result.content : []
99
+ const text = blocks
100
+ .filter((block) => block?.type === 'text' && typeof block.text === 'string')
101
+ .map((block) => block.text)
102
+ .join('\n')
103
+ return { text, isError: result?.isError === true }
104
+ }
105
+
106
+ // 工具清单在本机留一份:平台要求登记工具时当场给出清单、等不了一次请求的(OpenClaw 的工具工厂是同步的),
107
+ // 先用这一份,取到新的再换。和地址、访问密钥放在同一个目录,记着是哪个地址的清单
108
+ export function toolCacheFile(platform, env) {
109
+ return profileFile(platform, env).replace(/\.json$/, '-tools.json')
110
+ }
111
+
112
+ // 同步读这一份;没有、读不懂时为 null。at 是取到这份清单的时刻(毫秒),没记时为 0
113
+ export function readToolCacheSync(platform, env) {
114
+ try {
115
+ const data = JSON.parse(readFileSync(toolCacheFile(platform, env), 'utf8'))
116
+ if (typeof data?.url !== 'string') return null
117
+ const at = Number.isFinite(data.at) && data.at > 0 ? data.at : 0
118
+ return { url: data.url, at, tools: toolsOf(data) }
119
+ } catch {
120
+ return null
121
+ }
122
+ }
123
+
124
+ // 写不进去不算失败:下次再取
125
+ export async function writeToolCache(platform, { url, tools, at = Date.now() }, env) {
126
+ const file = toolCacheFile(platform, env)
127
+ const temp = `${file}.${randomUUID()}.tmp`
128
+ try {
129
+ await mkdir(profileDir(env), { recursive: true, mode: 0o700 })
130
+ await writeFile(temp, `${JSON.stringify({ url, at, tools })}\n`, { mode: 0o600, flag: 'wx' })
131
+ await chmod(temp, 0o600)
132
+ await rename(temp, file)
133
+ return true
134
+ } catch {
135
+ await rm(temp, { force: true }).catch(() => {})
136
+ return false
137
+ }
138
+ }
139
+
140
+ export async function removeToolCache(platform, env) {
141
+ await rm(toolCacheFile(platform, env), { force: true }).catch(() => {})
142
+ }
@@ -0,0 +1,100 @@
1
+ // 没有自己的密钥存储的平台(Codex、pi 这类),地址与访问密钥放在本机的一个文件里:
2
+ // <配置目录>/kioku/<平台>.json,只给本人读写。kioku setup 写它,各平台的钩子与 kioku doctor 读它。
3
+ // 一个平台一个文件:每个平台在 Kioku 里是各自的应用,访问密钥不共用
4
+
5
+ import { randomUUID } from 'node:crypto'
6
+ import { chmod, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
7
+ import { homedir } from 'node:os'
8
+ import { join } from 'node:path'
9
+
10
+ import { errorKind, keyFormatError, KiokuFailure } from './http.mjs'
11
+
12
+ // 平台名要拼进文件名,只收这些字符
13
+ const PLATFORM = /^[a-z][a-z0-9-]{0,31}$/
14
+
15
+ // 放这些文件的目录:KIOKU_CONFIG_DIR,否则 XDG 的配置目录下的 kioku
16
+ export function profileDir(env) {
17
+ if (env.KIOKU_CONFIG_DIR) return env.KIOKU_CONFIG_DIR
18
+ return join(env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'kioku')
19
+ }
20
+
21
+ export function profileFile(platform, env) {
22
+ if (!PLATFORM.test(platform)) throw new KiokuFailure('平台名不对')
23
+ return join(profileDir(env), `${platform}.json`)
24
+ }
25
+
26
+ // 服务地址:去掉首尾空白与结尾的斜杠;不是 http(s) 地址、或者带着账号密码、查询参数时返回原因
27
+ export function serverUrlProblem(url) {
28
+ // URL 解析会悄悄去掉中间的换行与制表符:原样写进配置文件的是带着它们的那一份
29
+ if (/[\s\p{Cc}]/u.test(url)) return '服务地址里不能有空白或控制字符'
30
+ let parsed
31
+ try {
32
+ parsed = new URL(url)
33
+ } catch {
34
+ return '服务地址不是有效的地址'
35
+ }
36
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
37
+ return '服务地址要以 http:// 或 https:// 开头'
38
+ }
39
+ if (parsed.username || parsed.password || parsed.search || parsed.hash) {
40
+ return '服务地址里不要带账号密码、查询参数'
41
+ }
42
+ return null
43
+ }
44
+
45
+ // 读这个平台的地址与访问密钥。没有这个文件时为 null;文件读不懂、内容不对时抛 KiokuFailure,
46
+ // 文字只写文件的位置与问题,不带内容
47
+ export async function readProfile(platform, env) {
48
+ const file = profileFile(platform, env)
49
+ let text
50
+ try {
51
+ text = await readFile(file, 'utf8')
52
+ } catch (err) {
53
+ if (err?.code === 'ENOENT') return null
54
+ throw new KiokuFailure(`无法读取 ${file}(${errorKind(err)})`)
55
+ }
56
+ let data
57
+ try {
58
+ data = JSON.parse(text)
59
+ } catch {
60
+ data = null
61
+ }
62
+ const url = typeof data?.serverUrl === 'string' ? data.serverUrl.trim().replace(/\/+$/, '') : ''
63
+ const key = typeof data?.apiKey === 'string' ? data.apiKey.trim() : ''
64
+ if (!url || !key) throw new KiokuFailure(`${file} 里没有服务地址或访问密钥`)
65
+ const problem = serverUrlProblem(url) ?? keyFormatError(key)
66
+ if (problem) throw new KiokuFailure(`${file}:${problem}`)
67
+ return { url, key, file }
68
+ }
69
+
70
+ // 写这个平台的地址与访问密钥:目录与文件都只给本人,先写临时文件再改名
71
+ export async function writeProfile(platform, { url, key }, env) {
72
+ const file = profileFile(platform, env)
73
+ const clean = url.trim().replace(/\/+$/, '')
74
+ const problem = serverUrlProblem(clean) ?? keyFormatError(key)
75
+ if (problem) throw new KiokuFailure(problem)
76
+ const temp = `${file}.${randomUUID()}.tmp`
77
+ try {
78
+ await mkdir(profileDir(env), { recursive: true, mode: 0o700 })
79
+ const body = `${JSON.stringify({ serverUrl: clean, apiKey: key }, null, 2)}\n`
80
+ await writeFile(temp, body, { mode: 0o600, flag: 'wx' })
81
+ // 已有的文件权限可能更宽,改名之后以新文件的为准;再收一次,不受 umask 影响
82
+ await chmod(temp, 0o600)
83
+ await rename(temp, file)
84
+ } catch (err) {
85
+ await rm(temp, { force: true }).catch(() => {})
86
+ throw new KiokuFailure(`无法写入 ${file}(${errorKind(err)})`)
87
+ }
88
+ return file
89
+ }
90
+
91
+ export async function removeProfile(platform, env) {
92
+ const file = profileFile(platform, env)
93
+ try {
94
+ await rm(file)
95
+ return file
96
+ } catch (err) {
97
+ if (err?.code === 'ENOENT') return null
98
+ throw new KiokuFailure(`无法删除 ${file}(${errorKind(err)})`)
99
+ }
100
+ }