@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/LICENSE +202 -0
- package/NOTICE +7 -0
- package/README.md +72 -2
- package/index.js +17 -0
- package/kioku.js +365 -0
- package/lib/api.mjs +35 -0
- package/lib/codex.mjs +309 -0
- package/lib/command.mjs +135 -0
- package/lib/config.mjs +50 -0
- package/lib/doctor.mjs +145 -0
- package/lib/dsh.mjs +75 -0
- package/lib/files.mjs +92 -0
- package/lib/hermes.mjs +261 -0
- package/lib/http.mjs +57 -0
- package/lib/import.mjs +262 -0
- package/lib/kioku.mjs +424 -0
- package/lib/lifecycle.mjs +118 -0
- package/lib/login.mjs +257 -0
- package/lib/mcp.mjs +142 -0
- package/lib/openclaw.mjs +248 -0
- package/lib/pi.mjs +81 -0
- package/lib/platforms.mjs +137 -0
- package/lib/profile.mjs +100 -0
- package/lib/redact.mjs +91 -0
- package/lib/secret.mjs +86 -0
- package/lib/setup.mjs +112 -0
- package/lib/sources.mjs +333 -0
- package/lib/target.mjs +62 -0
- package/lib/text.mjs +14 -0
- package/lib/usage.mjs +2 -0
- package/openclaw.plugin.json +28 -0
- package/package.json +40 -4
|
@@ -0,0 +1,118 @@
|
|
|
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 hostOutput.value?.hookSpecificOutput?.additionalContext
|
|
89
|
+
if (hostOutput?.mode === 'stdout_text') return hostOutput.value
|
|
90
|
+
// 没有专门输出格式的运行时:服务端直接给文本
|
|
91
|
+
if (hostOutput?.mode === 'return_value') return hostOutput.value?.context
|
|
92
|
+
return undefined
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// 把一个生命周期事件交给服务端;连不上、超时、取消、跳转与非 2xx 都以 KiokuFailure 抛出
|
|
96
|
+
export async function postEvent(base, key, body, timeout, signal) {
|
|
97
|
+
let res
|
|
98
|
+
try {
|
|
99
|
+
res = await fetch(`${base}/v1/lifecycle/event`, {
|
|
100
|
+
method: 'POST',
|
|
101
|
+
headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
|
|
102
|
+
body: JSON.stringify(body),
|
|
103
|
+
redirect: 'manual',
|
|
104
|
+
// 宿主给了中止信号时(用户取消了这次输入)一起听
|
|
105
|
+
signal: signal
|
|
106
|
+
? AbortSignal.any([AbortSignal.timeout(timeout), signal])
|
|
107
|
+
: AbortSignal.timeout(timeout),
|
|
108
|
+
})
|
|
109
|
+
} catch (err) {
|
|
110
|
+
if (signal?.aborted) throw new KiokuFailure('已取消')
|
|
111
|
+
throw new KiokuFailure(fetchFailure(err, timeout))
|
|
112
|
+
}
|
|
113
|
+
if (isRedirect(res.status)) {
|
|
114
|
+
throw new Misconfigured(redirectError(res.status, res.headers.get('location'), base), 'url')
|
|
115
|
+
}
|
|
116
|
+
if (!res.ok) throw new KiokuFailure(`HTTP ${res.status}`)
|
|
117
|
+
return res
|
|
118
|
+
}
|
package/lib/login.mjs
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
// kioku login:浏览器授权。命令行向 Kioku 申请,显示一个确认码;用户在管理界面的确认页输入它、
|
|
2
|
+
// 选好空间与权限后确认,命令行取走访问密钥,交给这个平台的 kioku setup 写下。
|
|
3
|
+
// 访问密钥不显示、不写进输出;确认码不放进打开的地址里,要用户照着终端输入:别人发来的链接带不了它。
|
|
4
|
+
// 服务端的回答不全信:确认页的路径只收一种写法,时限与间隔收在一个范围里
|
|
5
|
+
|
|
6
|
+
import { spawn } from 'node:child_process'
|
|
7
|
+
import { hostname } from 'node:os'
|
|
8
|
+
|
|
9
|
+
import { fetchFailure, isRedirect, KiokuFailure, redirectError } from './http.mjs'
|
|
10
|
+
import { platformNames, PLATFORMS } from './platforms.mjs'
|
|
11
|
+
import { resolveServerUrl } from './target.mjs'
|
|
12
|
+
import { plain } from './text.mjs'
|
|
13
|
+
import { UsageError } from './usage.mjs'
|
|
14
|
+
|
|
15
|
+
export const LOGIN_USAGE = `用法:kioku login <平台> [--server-url <地址>] [--no-browser]
|
|
16
|
+
|
|
17
|
+
用浏览器授权给这个平台签发一个访问密钥并配好,不用手动复制:终端显示一个确认码,
|
|
18
|
+
在 Kioku 管理界面的确认页输入它,选好空间与权限后确认。
|
|
19
|
+
|
|
20
|
+
<平台> ${platformNames()}(Claude Code 的访问密钥在它的 /plugin 里填,不走这里)
|
|
21
|
+
--server-url <地址> Kioku 的服务地址,例如 https://kioku.example.com(也可以用 KIOKU_SERVER_URL;配过的沿用上次的)
|
|
22
|
+
--no-browser 不自动打开浏览器,只显示地址
|
|
23
|
+
|
|
24
|
+
只在自己刚运行了这条命令时确认:确认之后,这台机器会拿到一个能按所选权限读写记忆的访问密钥。
|
|
25
|
+
`
|
|
26
|
+
|
|
27
|
+
const TIMEOUT = 8000
|
|
28
|
+
// 连着这么多次没得到回答(连不上、服务端 5xx)才放弃:等确认的这几分钟里抖一下不算失败
|
|
29
|
+
const MAX_FAILURES = 5
|
|
30
|
+
// 确认页的路径只收这种写法:接在服务地址后面打开,不带查询参数与别的符号
|
|
31
|
+
const VERIFICATION_PATH = /^\/[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*$/
|
|
32
|
+
// 服务端给的时限与间隔收在这个范围里(秒):给得再离谱也不会一直等、不会忙等
|
|
33
|
+
const MAX_EXPIRES = 1800
|
|
34
|
+
const MIN_INTERVAL = 1
|
|
35
|
+
const MAX_INTERVAL = 60
|
|
36
|
+
|
|
37
|
+
// 地址返回了跳转:配置的问题,重试没有用
|
|
38
|
+
class Redirected extends KiokuFailure {}
|
|
39
|
+
|
|
40
|
+
// 取走访问密钥这一步之后出的问题:访问密钥可能已经签发、却没有落到这台机器上
|
|
41
|
+
const ORPHAN_HINT =
|
|
42
|
+
'如果确认页上已经点了确认,可能已经签发了一个没被取走的访问密钥:到管理界面的应用页吊销它,再重新运行'
|
|
43
|
+
|
|
44
|
+
async function post(url, path, body) {
|
|
45
|
+
let res
|
|
46
|
+
let data
|
|
47
|
+
try {
|
|
48
|
+
res = await fetch(`${url}${path}`, {
|
|
49
|
+
method: 'POST',
|
|
50
|
+
headers: { 'content-type': 'application/json' },
|
|
51
|
+
body: JSON.stringify(body),
|
|
52
|
+
// 不跟着跳转走:设备码只发给配置的地址
|
|
53
|
+
redirect: 'manual',
|
|
54
|
+
signal: AbortSignal.timeout(TIMEOUT),
|
|
55
|
+
})
|
|
56
|
+
data = await res.json().catch(() => null)
|
|
57
|
+
} catch (err) {
|
|
58
|
+
throw new KiokuFailure(fetchFailure(err, TIMEOUT))
|
|
59
|
+
}
|
|
60
|
+
if (isRedirect(res.status)) {
|
|
61
|
+
throw new Redirected(redirectError(res.status, res.headers.get('location'), url))
|
|
62
|
+
}
|
|
63
|
+
return { status: res.status, data }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// 服务端给的秒数收进范围;不是有限的正数时用默认值
|
|
67
|
+
function seconds(value, fallback, min, max) {
|
|
68
|
+
const number = typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : fallback
|
|
69
|
+
return Math.min(max, Math.max(min, number))
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// 申请:返回设备码、确认码、确认页的地址与时限
|
|
73
|
+
export async function requestGrant(url, { runtimeFamily, clientName }) {
|
|
74
|
+
const { status, data } = await post(url, '/v1/device/authorize', {
|
|
75
|
+
runtimeFamily,
|
|
76
|
+
...(clientName ? { clientName } : {}),
|
|
77
|
+
})
|
|
78
|
+
if (status === 404) {
|
|
79
|
+
throw new KiokuFailure(
|
|
80
|
+
'这个 Kioku 还不支持浏览器授权:升级服务端,或者用 kioku setup 手动填访问密钥',
|
|
81
|
+
)
|
|
82
|
+
}
|
|
83
|
+
if (status === 429) throw new KiokuFailure('待确认的申请太多,稍后再试')
|
|
84
|
+
if (status !== 201) throw new KiokuFailure(`Kioku 返回 HTTP ${status}`)
|
|
85
|
+
if (
|
|
86
|
+
typeof data?.deviceCode !== 'string' ||
|
|
87
|
+
!data.deviceCode ||
|
|
88
|
+
typeof data.userCode !== 'string' ||
|
|
89
|
+
typeof data.verificationPath !== 'string' ||
|
|
90
|
+
!VERIFICATION_PATH.test(data.verificationPath)
|
|
91
|
+
) {
|
|
92
|
+
throw new KiokuFailure('Kioku 的响应格式不对')
|
|
93
|
+
}
|
|
94
|
+
return {
|
|
95
|
+
deviceCode: data.deviceCode,
|
|
96
|
+
userCode: data.userCode,
|
|
97
|
+
verificationUrl: `${url}${data.verificationPath}`,
|
|
98
|
+
expiresIn: seconds(data.expiresIn, 600, 1, MAX_EXPIRES),
|
|
99
|
+
interval: seconds(data.interval, 3, MIN_INTERVAL, MAX_INTERVAL),
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// 等确认:按服务端给的间隔轮询,返回访问密钥与应用;被拒绝、过期时抛 KiokuFailure。
|
|
104
|
+
// sleep 与 now 可以换掉,给用例用;now 要是只往前走的钟,系统时间被改不影响什么时候停
|
|
105
|
+
export async function waitForKey(
|
|
106
|
+
url,
|
|
107
|
+
grant,
|
|
108
|
+
{
|
|
109
|
+
sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
110
|
+
now = () => performance.now(),
|
|
111
|
+
} = {},
|
|
112
|
+
) {
|
|
113
|
+
const deadline = now() + grant.expiresIn * 1000
|
|
114
|
+
let interval = grant.interval * 1000
|
|
115
|
+
let failures = 0
|
|
116
|
+
// 有过没得到回答的轮询:那一次服务端可能已经把访问密钥签出来了
|
|
117
|
+
let missed = false
|
|
118
|
+
while (now() < deadline) {
|
|
119
|
+
await sleep(interval)
|
|
120
|
+
let answer
|
|
121
|
+
try {
|
|
122
|
+
answer = await post(url, '/v1/device/token', { deviceCode: grant.deviceCode })
|
|
123
|
+
} catch (err) {
|
|
124
|
+
if (err instanceof Redirected) throw err
|
|
125
|
+
missed = true
|
|
126
|
+
if (++failures >= MAX_FAILURES) throw new KiokuFailure(`${err.message}。${ORPHAN_HINT}`)
|
|
127
|
+
continue
|
|
128
|
+
}
|
|
129
|
+
const { status, data } = answer
|
|
130
|
+
// 服务端嫌太勤:隔久一点
|
|
131
|
+
if (status === 429) {
|
|
132
|
+
interval = Math.min(interval + 1000, MAX_INTERVAL * 1000)
|
|
133
|
+
continue
|
|
134
|
+
}
|
|
135
|
+
// 服务端一时出错(重启、网关)和连不上一样,过会儿再问
|
|
136
|
+
if (status >= 500) {
|
|
137
|
+
missed = true
|
|
138
|
+
if (++failures >= MAX_FAILURES) {
|
|
139
|
+
throw new KiokuFailure(`Kioku 返回 HTTP ${status}。${ORPHAN_HINT}`)
|
|
140
|
+
}
|
|
141
|
+
continue
|
|
142
|
+
}
|
|
143
|
+
if (status !== 200) throw new KiokuFailure(`Kioku 返回 HTTP ${status}`)
|
|
144
|
+
failures = 0
|
|
145
|
+
if (data?.status === 'pending') continue
|
|
146
|
+
if (data?.status === 'denied') {
|
|
147
|
+
throw new KiokuFailure('申请被拒绝了,或者确认之后确认人的权限变了:没有签发访问密钥')
|
|
148
|
+
}
|
|
149
|
+
if (data?.status === 'approved' && typeof data.key === 'string' && data.key) {
|
|
150
|
+
return { key: data.key, app: data.app ?? {} }
|
|
151
|
+
}
|
|
152
|
+
if (data?.status === 'expired') break
|
|
153
|
+
throw new KiokuFailure('Kioku 的响应格式不对')
|
|
154
|
+
}
|
|
155
|
+
throw new KiokuFailure(
|
|
156
|
+
missed
|
|
157
|
+
? `申请已经不在了,没有取到访问密钥。${ORPHAN_HINT}`
|
|
158
|
+
: '申请过期了,没有等到确认:重新运行 kioku login',
|
|
159
|
+
)
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// 用系统默认的浏览器打开地址;打不开就算了,地址已经显示在终端里。都不经过 shell:
|
|
163
|
+
// Windows 上用 rundll32,不用 cmd 的 start(它会把地址里的 & 这类符号当成命令)
|
|
164
|
+
function openBrowser(address) {
|
|
165
|
+
const [command, args] =
|
|
166
|
+
process.platform === 'darwin'
|
|
167
|
+
? ['open', [address]]
|
|
168
|
+
: process.platform === 'win32'
|
|
169
|
+
? ['rundll32', ['url.dll,FileProtocolHandler', address]]
|
|
170
|
+
: ['xdg-open', [address]]
|
|
171
|
+
try {
|
|
172
|
+
const child = spawn(command, args, { stdio: 'ignore', detached: true })
|
|
173
|
+
child.on('error', () => {})
|
|
174
|
+
child.unref()
|
|
175
|
+
} catch {
|
|
176
|
+
// 没有图形界面
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// 走一遍浏览器授权,返回访问密钥。提示写到 out,访问密钥不写
|
|
181
|
+
export async function deviceLogin(
|
|
182
|
+
{ url, runtimeFamily },
|
|
183
|
+
{ out, open = openBrowser, browser = true, clientName = hostname(), sleep, now } = {},
|
|
184
|
+
) {
|
|
185
|
+
// 机器名是自报的:去掉控制字符,太长就截断,服务端只把它显示在确认页上
|
|
186
|
+
const name = Array.from(plain(clientName)).slice(0, 64).join('')
|
|
187
|
+
const grant = await requestGrant(url, { runtimeFamily, clientName: name })
|
|
188
|
+
out.write(`确认码:${plain(grant.userCode)}\n`)
|
|
189
|
+
// 显示的和打开的是同一个地址
|
|
190
|
+
out.write(`在浏览器里打开 ${plain(grant.verificationUrl)},登录后输入这个确认码\n`)
|
|
191
|
+
out.write(`等待确认(${Math.ceil(grant.expiresIn / 60)} 分钟内有效)…\n`)
|
|
192
|
+
if (browser) open(grant.verificationUrl)
|
|
193
|
+
const { key, app } = await waitForKey(url, grant, { sleep, now })
|
|
194
|
+
out.write(`✓ 已确认:应用 ${plain(app.name ?? '')}(${plain(app.slug ?? '')})\n`)
|
|
195
|
+
return key
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
export function parseLoginArgs(argv) {
|
|
199
|
+
const options = { serverUrl: undefined, browser: true }
|
|
200
|
+
const names = []
|
|
201
|
+
for (let i = 0; i < argv.length; i++) {
|
|
202
|
+
const arg = argv[i]
|
|
203
|
+
if (arg === '--no-browser') options.browser = false
|
|
204
|
+
else if (arg === '--server-url') {
|
|
205
|
+
options.serverUrl = argv[++i]
|
|
206
|
+
if (!options.serverUrl) throw new UsageError('--server-url 后面要写地址')
|
|
207
|
+
} else if (arg.startsWith('-')) throw new UsageError(`不认识的选项 ${arg}`)
|
|
208
|
+
else names.push(arg)
|
|
209
|
+
}
|
|
210
|
+
if (names.length !== 1) throw new UsageError('要写一个平台')
|
|
211
|
+
if (!Object.hasOwn(PLATFORMS, names[0])) {
|
|
212
|
+
throw new UsageError(`不认识的平台 ${names[0]},可以用的:${platformNames()}`)
|
|
213
|
+
}
|
|
214
|
+
if (!PLATFORMS[names[0]].setup) {
|
|
215
|
+
throw new UsageError(
|
|
216
|
+
`${PLATFORMS[names[0]].name} 的访问密钥在它自己的插件配置里填,不走 kioku login`,
|
|
217
|
+
)
|
|
218
|
+
}
|
|
219
|
+
return { ...options, platform: names[0] }
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
export async function login(
|
|
223
|
+
argv,
|
|
224
|
+
{
|
|
225
|
+
env = process.env,
|
|
226
|
+
out = process.stdout,
|
|
227
|
+
cwd = process.cwd(),
|
|
228
|
+
open,
|
|
229
|
+
sleep,
|
|
230
|
+
now,
|
|
231
|
+
clientName,
|
|
232
|
+
} = {},
|
|
233
|
+
) {
|
|
234
|
+
const options = parseLoginArgs(argv)
|
|
235
|
+
const platform = PLATFORMS[options.platform]
|
|
236
|
+
const saved = await Promise.resolve(platform.readConfig?.(env)).catch(() => null)
|
|
237
|
+
const url = resolveServerUrl(options, env, saved)
|
|
238
|
+
// 申请之前先看这个平台的配置写不写得进去:访问密钥只在签发时给一次
|
|
239
|
+
await platform.preflight?.({ env, cwd })
|
|
240
|
+
const key = await deviceLogin(
|
|
241
|
+
{ url, runtimeFamily: platform.runtimeFamily },
|
|
242
|
+
{ out, open, browser: options.browser, sleep, now, ...(clientName ? { clientName } : {}) },
|
|
243
|
+
)
|
|
244
|
+
// 拿到的访问密钥交给这个平台的 setup:核对、写文件都照它的规矩
|
|
245
|
+
try {
|
|
246
|
+
return await platform.setup(
|
|
247
|
+
{ serverUrl: url, dryRun: false, undo: false, check: true },
|
|
248
|
+
{ env, out, cwd, readKey: async () => key, plain, login: null },
|
|
249
|
+
)
|
|
250
|
+
} catch (err) {
|
|
251
|
+
if (!(err instanceof KiokuFailure)) throw err
|
|
252
|
+
// 访问密钥已经签发、却没有写下来:说清楚,别让它悄悄留着
|
|
253
|
+
throw new KiokuFailure(
|
|
254
|
+
`${err.message}。访问密钥已经签发、但没有写下:到管理界面的应用页吊销它,解决上面的问题后重新运行`,
|
|
255
|
+
)
|
|
256
|
+
}
|
|
257
|
+
}
|
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
|
+
}
|