@kioku-memory/plugin-opencode 0.0.0-stage → 0.1.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/login.mjs ADDED
@@ -0,0 +1,359 @@
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 { ensureNoConflicts } from './conflicts.mjs'
10
+ import { configure, orphanHint } from './connect.mjs'
11
+ import { fetchFailure, isRedirect, KiokuFailure, redirectError } from './http.mjs'
12
+ import { platformNames, PLATFORMS } from './platforms.mjs'
13
+ import { resolveServerUrl } from './target.mjs'
14
+ import { plain } from './text.mjs'
15
+ import { UsageError } from './usage.mjs'
16
+
17
+ export const LOGIN_USAGE = `用法:kioku login <平台> [--server-url <地址>] [--no-browser] [--remove-conflicts]
18
+
19
+ 用浏览器授权给这个平台签发一个访问密钥并配好,不用手动复制:终端显示一个确认码,
20
+ 在 Kioku 管理界面的确认页输入它,选好空间与权限后确认。
21
+
22
+ <平台> ${platformNames()}(Claude Code 的访问密钥在它的 /plugin 里填,不走这里)
23
+ --server-url <地址> Kioku 的服务地址,例如 https://kioku.example.com(也可以用 KIOKU_SERVER_URL;配过的沿用上次的)
24
+ --no-browser 不自动打开浏览器,只显示地址
25
+ --remove-conflicts 先卸载平台上已有的冲突记忆工具(Lore 及常见记忆 MCP)再继续
26
+
27
+ 只在自己刚运行了这条命令时确认:确认之后,这台机器会拿到一个能按所选权限读写记忆的访问密钥。
28
+ `
29
+
30
+ const TIMEOUT = 8000
31
+ // 连着这么多次没得到回答(连不上、服务端 5xx)才放弃:等确认的这几分钟里抖一下不算失败
32
+ const MAX_FAILURES = 5
33
+ // 确认页的路径只收这种写法:接在服务地址后面打开,不带查询参数与别的符号
34
+ const VERIFICATION_PATH = /^\/[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*$/
35
+ // 服务端给的时限与间隔收在这个范围里(秒):给得再离谱也不会一直等、不会忙等
36
+ const MAX_EXPIRES = 1800
37
+ const MIN_INTERVAL = 1
38
+ const MAX_INTERVAL = 60
39
+
40
+ // 地址返回了跳转:配置的问题,重试没有用
41
+ class Redirected extends KiokuFailure {}
42
+
43
+ // 取走访问密钥这一步之后出的问题:访问密钥可能已经签发、却没有落到这台机器上
44
+ const ORPHAN_HINT =
45
+ '如果确认页上已经点了确认,可能已经签发了一个没被取走的访问密钥:到管理界面的应用页吊销它,再重新运行'
46
+
47
+ async function post(url, path, body) {
48
+ let res
49
+ let data
50
+ try {
51
+ res = await fetch(`${url}${path}`, {
52
+ method: 'POST',
53
+ headers: { 'content-type': 'application/json' },
54
+ body: JSON.stringify(body),
55
+ // 不跟着跳转走:设备码只发给配置的地址
56
+ redirect: 'manual',
57
+ signal: AbortSignal.timeout(TIMEOUT),
58
+ })
59
+ data = await res.json().catch(() => null)
60
+ } catch (err) {
61
+ throw new KiokuFailure(fetchFailure(err, TIMEOUT))
62
+ }
63
+ if (isRedirect(res.status)) {
64
+ throw new Redirected(redirectError(res.status, res.headers.get('location'), url))
65
+ }
66
+ return { status: res.status, data }
67
+ }
68
+
69
+ // 服务端给的秒数收进范围;不是有限的正数时用默认值
70
+ function seconds(value, fallback, min, max) {
71
+ const number = typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : fallback
72
+ return Math.min(max, Math.max(min, number))
73
+ }
74
+
75
+ // 服务端不认一次申请几个平台的写法:退回逐个平台申请
76
+ export class LegacyServer extends KiokuFailure {}
77
+
78
+ // 旧的服务端只认单个平台的写法,收到 platforms 时按校验失败回 400,第一条问题是缺 runtimeFamily
79
+ // (「runtimeFamily:…」)。别的 400 是申请本身有问题,照原样报
80
+ function legacyRejection(data) {
81
+ return typeof data?.error === 'string' && /^runtimeFamily[::]/.test(data.error)
82
+ }
83
+
84
+ // 一次申请最多几个平台,与服务端的上限一致
85
+ export const MAX_PLATFORMS = 8
86
+
87
+ // 申请:返回设备码、确认码、确认页的地址与时限。body 是单平台的 { runtimeFamily, clientName },
88
+ // 或几个平台的 { platforms: [{ runtimeFamily }], clientName }
89
+ export async function requestGrant(url, body) {
90
+ const { clientName, ...rest } = body
91
+ const { status, data } = await post(url, '/v1/device/authorize', {
92
+ ...rest,
93
+ ...(clientName ? { clientName } : {}),
94
+ })
95
+ if (status === 400 && Array.isArray(body.platforms) && legacyRejection(data)) {
96
+ throw new LegacyServer('服务端版本较旧,需要逐个确认')
97
+ }
98
+ if (status === 400) {
99
+ const reason = typeof data?.error === 'string' ? plain(data.error) : ''
100
+ throw new KiokuFailure(`Kioku 拒绝了这次申请${reason ? `:${reason}` : ''}`)
101
+ }
102
+ if (status === 404) {
103
+ throw new KiokuFailure(
104
+ '这个 Kioku 还不支持浏览器授权:升级服务端,或者用 kioku setup 手动填访问密钥',
105
+ )
106
+ }
107
+ if (status === 429) throw new KiokuFailure('待确认的申请太多,稍后再试')
108
+ if (status !== 201) throw new KiokuFailure(`Kioku 返回 HTTP ${status}`)
109
+ if (
110
+ typeof data?.deviceCode !== 'string' ||
111
+ !data.deviceCode ||
112
+ typeof data.userCode !== 'string' ||
113
+ typeof data.verificationPath !== 'string' ||
114
+ !VERIFICATION_PATH.test(data.verificationPath)
115
+ ) {
116
+ throw new KiokuFailure('Kioku 的响应格式不对')
117
+ }
118
+ return {
119
+ deviceCode: data.deviceCode,
120
+ userCode: data.userCode,
121
+ verificationUrl: `${url}${data.verificationPath}`,
122
+ expiresIn: seconds(data.expiresIn, 600, 1, MAX_EXPIRES),
123
+ interval: seconds(data.interval, 3, MIN_INTERVAL, MAX_INTERVAL),
124
+ }
125
+ }
126
+
127
+ // 等确认:按服务端给的间隔轮询,确认了返回服务端的整个回答;被拒绝、过期时抛 KiokuFailure。
128
+ // sleep 与 now 可以换掉,给用例用;now 要是只往前走的钟,系统时间被改不影响什么时候停
129
+ async function waitForApproval(
130
+ url,
131
+ grant,
132
+ {
133
+ sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
134
+ now = () => performance.now(),
135
+ } = {},
136
+ ) {
137
+ const deadline = now() + grant.expiresIn * 1000
138
+ let interval = grant.interval * 1000
139
+ let failures = 0
140
+ // 有过没得到回答的轮询:那一次服务端可能已经把访问密钥签出来了
141
+ let missed = false
142
+ while (now() < deadline) {
143
+ await sleep(interval)
144
+ let answer
145
+ try {
146
+ answer = await post(url, '/v1/device/token', { deviceCode: grant.deviceCode })
147
+ } catch (err) {
148
+ if (err instanceof Redirected) throw err
149
+ missed = true
150
+ if (++failures >= MAX_FAILURES) throw new KiokuFailure(`${err.message}。${ORPHAN_HINT}`)
151
+ continue
152
+ }
153
+ const { status, data } = answer
154
+ // 服务端嫌太勤:隔久一点
155
+ if (status === 429) {
156
+ interval = Math.min(interval + 1000, MAX_INTERVAL * 1000)
157
+ continue
158
+ }
159
+ // 服务端一时出错(重启、网关)和连不上一样,过会儿再问
160
+ if (status >= 500) {
161
+ missed = true
162
+ if (++failures >= MAX_FAILURES) {
163
+ throw new KiokuFailure(`Kioku 返回 HTTP ${status}。${ORPHAN_HINT}`)
164
+ }
165
+ continue
166
+ }
167
+ if (status !== 200) throw new KiokuFailure(`Kioku 返回 HTTP ${status}`)
168
+ failures = 0
169
+ if (data?.status === 'pending') continue
170
+ if (data?.status === 'denied') {
171
+ throw new KiokuFailure('申请被拒绝了,或者确认之后确认人的权限变了:没有签发访问密钥')
172
+ }
173
+ if (data?.status === 'approved') return data
174
+ if (data?.status === 'expired') break
175
+ throw new KiokuFailure('Kioku 的响应格式不对')
176
+ }
177
+ throw new KiokuFailure(
178
+ missed
179
+ ? `申请已经不在了,没有取到访问密钥。${ORPHAN_HINT}`
180
+ : '申请过期了,没有等到确认:重新运行 kioku login',
181
+ )
182
+ }
183
+
184
+ // 等一个平台的申请被确认,返回访问密钥与应用
185
+ export async function waitForKey(url, grant, options) {
186
+ const data = await waitForApproval(url, grant, options)
187
+ if (typeof data.key !== 'string' || !data.key) throw new KiokuFailure('Kioku 的响应格式不对')
188
+ return { key: data.key, app: data.app ?? {} }
189
+ }
190
+
191
+ // 几个平台一起的申请被确认之后,每个平台的结果:按申请的顺序,
192
+ // { runtimeFamily, status: 'issued', key, app } | { runtimeFamily, status: 'skipped' } | { runtimeFamily, status: 'denied', reason }。
193
+ // 服务端没提到的平台算跳过,不认识的平台、重复的项不收;签发了却不像访问密钥的算响应不对
194
+ export async function waitForKeys(url, grant, families, options) {
195
+ const data = await waitForApproval(url, grant, options)
196
+ // 已经确认了:响应读不懂时,服务端可能已经签发了几个没人拿着的访问密钥
197
+ const malformed = () => new KiokuFailure(`Kioku 的响应格式不对。${ORPHAN_HINT}`)
198
+ if (!Array.isArray(data.keys)) throw malformed()
199
+ const byFamily = new Map()
200
+ for (const item of data.keys) {
201
+ const family = item?.runtimeFamily
202
+ if (!families.includes(family) || byFamily.has(family)) continue
203
+ if (item.status === 'issued') {
204
+ if (typeof item.key !== 'string' || !item.key) throw malformed()
205
+ byFamily.set(family, {
206
+ runtimeFamily: family,
207
+ status: 'issued',
208
+ key: item.key,
209
+ app: item.app ?? {},
210
+ })
211
+ } else if (item.status === 'denied') {
212
+ const reason = typeof item.reason === 'string' ? plain(item.reason) : ''
213
+ byFamily.set(family, { runtimeFamily: family, status: 'denied', reason })
214
+ } else byFamily.set(family, { runtimeFamily: family, status: 'skipped' })
215
+ }
216
+ return families.map(
217
+ (family) => byFamily.get(family) ?? { runtimeFamily: family, status: 'skipped' },
218
+ )
219
+ }
220
+
221
+ // 用系统默认的浏览器打开地址;打不开就算了,地址已经显示在终端里。都不经过 shell:
222
+ // Windows 上用 rundll32,不用 cmd 的 start(它会把地址里的 & 这类符号当成命令)
223
+ export function openBrowser(address) {
224
+ const [command, args] =
225
+ process.platform === 'darwin'
226
+ ? ['open', [address]]
227
+ : process.platform === 'win32'
228
+ ? ['rundll32', ['url.dll,FileProtocolHandler', address]]
229
+ : ['xdg-open', [address]]
230
+ try {
231
+ const child = spawn(command, args, { stdio: 'ignore', detached: true })
232
+ child.on('error', () => {})
233
+ child.unref()
234
+ } catch {
235
+ // 没有图形界面
236
+ }
237
+ }
238
+
239
+ // 本地网络给主机名加的后缀,不算机器的名字
240
+ const HOST_SUFFIX = /\.(?:local|localdomain|lan|home|internal)$/i
241
+
242
+ // 机器名是自报的:去掉控制字符与 .local 这类后缀,太长就截断;什么都不剩时用 kioku-cli。
243
+ // 服务端把它显示在确认页上,新建的应用默认叫「平台名 · 机器名」
244
+ export function machineName(clientName) {
245
+ const name = Array.from(plain(clientName).replace(HOST_SUFFIX, '').trim())
246
+ .slice(0, 64)
247
+ .join('')
248
+ .trim()
249
+ return name || 'kioku-cli'
250
+ }
251
+
252
+ // 显示确认码与确认页,打开浏览器
253
+ function showGrant(grant, { out, open, browser }) {
254
+ out.write(`确认码:${plain(grant.userCode)}\n`)
255
+ // 显示的和打开的是同一个地址
256
+ out.write(`在浏览器里打开 ${plain(grant.verificationUrl)},登录后输入这个确认码\n`)
257
+ out.write(`等待确认(${Math.ceil(grant.expiresIn / 60)} 分钟内有效)…\n`)
258
+ if (browser) open(grant.verificationUrl)
259
+ }
260
+
261
+ // 走一遍浏览器授权,返回访问密钥。提示写到 out,访问密钥不写
262
+ export async function deviceLogin(
263
+ { url, runtimeFamily },
264
+ { out, open = openBrowser, browser = true, clientName = hostname(), sleep, now } = {},
265
+ ) {
266
+ const grant = await requestGrant(url, { runtimeFamily, clientName: machineName(clientName) })
267
+ showGrant(grant, { out, open, browser })
268
+ const { key, app } = await waitForKey(url, grant, { sleep, now })
269
+ out.write(`✓ 已确认:应用 ${plain(app.name ?? '')}(${plain(app.slug ?? '')})\n`)
270
+ return key
271
+ }
272
+
273
+ // 几个平台一起申请,只确认一次。返回 waitForKeys 的结果(按去重后的顺序);服务端不认这种写法时抛 LegacyServer。
274
+ // 一次最多 MAX_PLATFORMS 个,多了由调用方分批(connect.mjs),这里不发超出上限的申请
275
+ export async function deviceLoginMany(
276
+ { url, runtimeFamilies },
277
+ { out, open = openBrowser, browser = true, clientName = hostname(), sleep, now } = {},
278
+ ) {
279
+ const families = [...new Set(runtimeFamilies)]
280
+ if (!families.length || families.length > MAX_PLATFORMS) {
281
+ throw new KiokuFailure(`一次申请 1 到 ${MAX_PLATFORMS} 个平台`)
282
+ }
283
+ const grant = await requestGrant(url, {
284
+ platforms: families.map((runtimeFamily) => ({ runtimeFamily })),
285
+ clientName: machineName(clientName),
286
+ })
287
+ showGrant(grant, { out, open, browser })
288
+ const results = await waitForKeys(url, grant, families, { sleep, now })
289
+ // 确认了也可能一个都没签发:取走时照签发规则再核对,全都没过(例如确认人已停用)
290
+ const issued = results.filter((item) => item.status === 'issued').length
291
+ out.write(issued ? `✓ 已确认,签发了 ${issued} 个访问密钥\n` : '✗ 已确认,但没有签发访问密钥\n')
292
+ return results
293
+ }
294
+
295
+ export function parseLoginArgs(argv) {
296
+ const options = { serverUrl: undefined, browser: true, removeConflicts: false }
297
+ const names = []
298
+ for (let i = 0; i < argv.length; i++) {
299
+ const arg = argv[i]
300
+ if (arg === '--no-browser') options.browser = false
301
+ else if (arg === '--remove-conflicts') options.removeConflicts = true
302
+ else if (arg === '--server-url') {
303
+ options.serverUrl = argv[++i]
304
+ if (!options.serverUrl) throw new UsageError('--server-url 后面要写地址')
305
+ } else if (arg.startsWith('-')) throw new UsageError(`不认识的选项 ${arg}`)
306
+ else names.push(arg)
307
+ }
308
+ if (names.length !== 1) throw new UsageError('要写一个平台')
309
+ if (!Object.hasOwn(PLATFORMS, names[0])) {
310
+ throw new UsageError(`不认识的平台 ${names[0]},可以用的:${platformNames()}`)
311
+ }
312
+ if (!PLATFORMS[names[0]].setup) {
313
+ throw new UsageError(
314
+ `${PLATFORMS[names[0]].name} 的访问密钥在它自己的插件配置里填,不走 kioku login`,
315
+ )
316
+ }
317
+ return { ...options, platform: names[0] }
318
+ }
319
+
320
+ export async function login(
321
+ argv,
322
+ {
323
+ env = process.env,
324
+ out = process.stdout,
325
+ cwd = process.cwd(),
326
+ stdin = process.stdin,
327
+ open,
328
+ sleep,
329
+ now,
330
+ clientName,
331
+ } = {},
332
+ ) {
333
+ const options = parseLoginArgs(argv)
334
+ const platform = PLATFORMS[options.platform]
335
+ const saved = await Promise.resolve(platform.readConfig?.(env)).catch(() => null)
336
+ const url = resolveServerUrl(options, env, saved)
337
+ // 申请之前先看这个平台的配置写不写得进去、有没有冲突:访问密钥只在签发时给一次
338
+ await platform.preflight?.({ env, cwd })
339
+ const conflictStatus = await ensureNoConflicts(options.platform, platform.name, {
340
+ env,
341
+ cwd,
342
+ out,
343
+ stdin,
344
+ remove: options.removeConflicts,
345
+ })
346
+ if (conflictStatus === 'cancelled') return 0
347
+ const key = await deviceLogin(
348
+ { url, runtimeFamily: platform.runtimeFamily },
349
+ { out, open, browser: options.browser, sleep, now, ...(clientName ? { clientName } : {}) },
350
+ )
351
+ // 拿到的访问密钥交给这个平台的 setup:核对、写文件都照它的规矩
352
+ try {
353
+ return await configure(options.platform, { url, key }, { env, out, cwd }, { hints: true })
354
+ } catch (err) {
355
+ if (!(err instanceof KiokuFailure)) throw err
356
+ // 访问密钥已经签发、却没有写下来:说清楚,别让它悄悄留着
357
+ throw new KiokuFailure(`${err.message}。${orphanHint()}`)
358
+ }
359
+ }
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
+ }