@kioku-memory/cli 0.2.0 → 0.4.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.
Files changed (62) hide show
  1. package/NOTICE +3 -0
  2. package/README.md +105 -25
  3. package/assets/plugins/agy/README.md +34 -0
  4. package/assets/plugins/agy/bin/kioku +36 -0
  5. package/assets/plugins/agy/hooks/forward.mjs +232 -0
  6. package/assets/plugins/agy/hooks.json +25 -0
  7. package/assets/plugins/agy/lib/kioku.mjs +53 -0
  8. package/{lib → assets/plugins/agy/lib}/lifecycle.mjs +13 -3
  9. package/{lib/kioku.mjs → assets/plugins/agy/lib/run.mjs} +4 -80
  10. package/assets/plugins/agy/package.json +7 -0
  11. package/assets/plugins/agy/plugin.json +6 -0
  12. package/assets/plugins/agy/vitest.config.mjs +5 -0
  13. package/assets/plugins/gemini/README.md +33 -0
  14. package/assets/plugins/gemini/bin/kioku +36 -0
  15. package/assets/plugins/gemini/gemini-extension.json +5 -0
  16. package/assets/plugins/gemini/hooks/forward.mjs +174 -0
  17. package/assets/plugins/gemini/hooks/hooks.json +43 -0
  18. package/assets/plugins/gemini/lib/command.mjs +152 -0
  19. package/assets/plugins/gemini/lib/config.mjs +50 -0
  20. package/assets/plugins/gemini/lib/http.mjs +57 -0
  21. package/assets/plugins/gemini/lib/kioku.mjs +53 -0
  22. package/assets/plugins/gemini/lib/lifecycle.mjs +128 -0
  23. package/assets/plugins/gemini/lib/mcp.mjs +142 -0
  24. package/assets/plugins/gemini/lib/profile.mjs +100 -0
  25. package/assets/plugins/gemini/lib/redact.mjs +91 -0
  26. package/assets/plugins/gemini/lib/run.mjs +372 -0
  27. package/assets/plugins/gemini/lib/text.mjs +14 -0
  28. package/assets/plugins/gemini/lib/usage.mjs +2 -0
  29. package/assets/plugins/gemini/package.json +7 -0
  30. package/assets/plugins/gemini/vitest.config.mjs +5 -0
  31. package/bin/kioku +16 -12
  32. package/dist/index.mjs +8846 -0
  33. package/package.json +14 -5
  34. package/lib/api.mjs +0 -38
  35. package/lib/codex.mjs +0 -320
  36. package/lib/connect.mjs +0 -152
  37. package/lib/doctor.mjs +0 -145
  38. package/lib/dsh.mjs +0 -82
  39. package/lib/files.mjs +0 -92
  40. package/lib/hermes.mjs +0 -276
  41. package/lib/import.mjs +0 -301
  42. package/lib/install.mjs +0 -146
  43. package/lib/local.mjs +0 -294
  44. package/lib/login.mjs +0 -347
  45. package/lib/openclaw.mjs +0 -256
  46. package/lib/panel.mjs +0 -295
  47. package/lib/pi.mjs +0 -90
  48. package/lib/platforms.mjs +0 -220
  49. package/lib/prompts.mjs +0 -38
  50. package/lib/secret.mjs +0 -86
  51. package/lib/setup.mjs +0 -112
  52. package/lib/sources.mjs +0 -333
  53. package/lib/target.mjs +0 -62
  54. package/lib/wizard.mjs +0 -447
  55. /package/{lib → assets/plugins/agy/lib}/command.mjs +0 -0
  56. /package/{lib → assets/plugins/agy/lib}/config.mjs +0 -0
  57. /package/{lib → assets/plugins/agy/lib}/http.mjs +0 -0
  58. /package/{lib → assets/plugins/agy/lib}/mcp.mjs +0 -0
  59. /package/{lib → assets/plugins/agy/lib}/profile.mjs +0 -0
  60. /package/{lib → assets/plugins/agy/lib}/redact.mjs +0 -0
  61. /package/{lib → assets/plugins/agy/lib}/text.mjs +0 -0
  62. /package/{lib → assets/plugins/agy/lib}/usage.mjs +0 -0
package/lib/local.mjs DELETED
@@ -1,294 +0,0 @@
1
- // 向导里的「本机起一个 Kioku」:在一个目录里放好 compose.yaml 与 .env,用 Docker 起服务,等它就绪,
2
- // 再等用户在管理界面建好第一个管理员。已有的文件不覆盖;端口被占时只说明,不动别的进程
3
-
4
- import { randomBytes } from 'node:crypto'
5
- import { chmod, mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises'
6
- import { connect, createServer } from 'node:net'
7
- import { homedir } from 'node:os'
8
- import { join, resolve } from 'node:path'
9
-
10
- import { capture } from './command.mjs'
11
- import { errorKind, KiokuFailure } from './http.mjs'
12
-
13
- const REPO = 'lonelyman0108/kioku'
14
- export const LATEST_RELEASE_URL = `https://api.github.com/repos/${REPO}/releases/latest`
15
-
16
- // 仓库里某个版本(tag 或分支)的文件
17
- export function rawUrl(ref, file) {
18
- return `https://raw.githubusercontent.com/${REPO}/${ref}/${file}`
19
- }
20
-
21
- // 用哪个版本:最新的正式版,compose.yaml、.env.example 从它的 tag 取,镜像固定在这个版本号;
22
- // 取不到时退回 main 上的文件与 edge 镜像(main 上最新的提交),problem 写明原因。
23
- // 返回 { ref, imageTag, release, problem? }
24
- export async function latestRelease({ fetchImpl = fetch } = {}) {
25
- let problem
26
- try {
27
- const res = await fetchImpl(LATEST_RELEASE_URL, {
28
- headers: { accept: 'application/vnd.github+json', 'user-agent': 'kioku-cli' },
29
- signal: AbortSignal.timeout(10_000),
30
- })
31
- const data = res.ok ? await res.json().catch(() => null) : null
32
- const tag = typeof data?.tag_name === 'string' ? data.tag_name : ''
33
- const match = /^v?(\d+\.\d+\.\d+)$/.exec(tag)
34
- if (match) return { ref: tag, imageTag: match[1], release: true }
35
- problem = res.ok ? '版本号认不出' : `HTTP ${res.status}`
36
- } catch (err) {
37
- problem = networkReason(err)
38
- }
39
- return { ref: 'main', imageTag: 'edge', release: false, problem }
40
- }
41
-
42
- // fetch 失败的原因:超时、错误码,或者笼统的网络错误
43
- function networkReason(err) {
44
- const code = err?.cause?.code
45
- if (err?.name === 'TimeoutError' || err?.name === 'AbortError') return '超时'
46
- return typeof code === 'string' && /^[A-Z][A-Z0-9_]*$/.test(code) ? code : '网络错误'
47
- }
48
- export const LOCAL_PORT = 18920
49
- export const LOCAL_URL = `http://127.0.0.1:${LOCAL_PORT}`
50
-
51
- export function defaultLocalDir(env) {
52
- return join(env.HOME || homedir(), 'kioku')
53
- }
54
-
55
- // 目录:~ 开头的换成主目录
56
- export function expandDir(dir, env) {
57
- const home = env.HOME || homedir()
58
- return resolve(dir === '~' ? home : dir.replace(/^~(?=[/\\])/, home))
59
- }
60
-
61
- // .env 里要生成的几项:两个数据库密码是 24 字节的十六进制(openssl rand -hex 24,只用十六进制字符,
62
- // 拼进连接串不出问题),主密钥是 32 字节的 base64,初始化码是 16 字节的十六进制
63
- export function generateSecrets(random = randomBytes) {
64
- return {
65
- POSTGRES_PASSWORD: random(24).toString('hex'),
66
- KIOKU_DB_PASSWORD: random(24).toString('hex'),
67
- KIOKU_MASTER_KEY: random(32).toString('base64'),
68
- KIOKU_SETUP_CODE: random(16).toString('hex'),
69
- }
70
- }
71
-
72
- // 只在本机用的设置:管理界面走 http://127.0.0.1,登录 Cookie 不能要求 HTTPS;端口只发布在本机
73
- export const LOCAL_SETTINGS = { KIOKU_COOKIE_SECURE: 'false', KIOKU_BIND: '127.0.0.1' }
74
-
75
- // 照着 .env.example 填:示例里有这一项就在原处填上;只有注释掉的(「# 名字=」)才填在注释那一行,
76
- // 免得说明里举的例子被填上、真正的那一行还空着(后出现的那行生效)。示例里没有的加在最后
77
- export function fillEnv(template, values) {
78
- const lines = template.split(/\r?\n/)
79
- const nameOf = (line, commented) =>
80
- (commented ? /^\s*#\s*([A-Z][A-Z0-9_]*)=/ : /^\s*([A-Z][A-Z0-9_]*)=/).exec(line)?.[1]
81
- const done = new Set()
82
- const next = [...lines]
83
- for (const commented of [false, true]) {
84
- next.forEach((line, index) => {
85
- const name = nameOf(line, commented)
86
- if (!name || !Object.hasOwn(values, name) || done.has(name)) return
87
- done.add(name)
88
- next[index] = `${name}=${values[name]}`
89
- })
90
- }
91
- while (next.length && next.at(-1) === '') next.pop()
92
- for (const [name, value] of Object.entries(values)) {
93
- if (!done.has(name)) next.push(`${name}=${value}`)
94
- }
95
- return `${next.join('\n')}\n`
96
- }
97
-
98
- // .env 里写的一项的值;没有为 null
99
- export function envValue(text, name) {
100
- for (const line of text.split(/\r?\n/)) {
101
- const match = /^\s*([A-Z][A-Z0-9_]*)=(.*)$/.exec(line)
102
- if (match?.[1] === name) return match[2].trim().replace(/^(["'])(.*)\1$/, '$2')
103
- }
104
- return null
105
- }
106
-
107
- // .env 里 KIOKU_TAG 上面的说明
108
- function tagNote(imageTag) {
109
- return imageTag === 'edge'
110
- ? '# 没取到最新的正式版,用的是 main 上最新的提交(edge),不保证稳定;改成版本号(如 0.1.0)固定下来'
111
- : `# 固定在 ${imageTag}(生成时的最新正式版)。升级时改这里,再 docker compose pull && docker compose up -d`
112
- }
113
-
114
- // 写 .env:只给本人读写,已有的不覆盖。imageTag 给了时 KIOKU_TAG 写成它,上面加一行说明。
115
- // 返回 { written, file, setupCode }:已有的文件不动,初始化码取它里面写的(没写为 null,要看日志)
116
- export async function writeEnvFile(dir, template, { random, imageTag } = {}) {
117
- const file = join(dir, '.env')
118
- const existing = await readFile(file, 'utf8').catch((err) => {
119
- if (err?.code === 'ENOENT') return null
120
- throw new KiokuFailure(`无法读取 ${file}(${errorKind(err)})`)
121
- })
122
- if (existing !== null) {
123
- return { written: false, file, setupCode: envValue(existing, 'KIOKU_SETUP_CODE') || null }
124
- }
125
- const secrets = generateSecrets(random)
126
- let body = fillEnv(template, {
127
- ...secrets,
128
- ...LOCAL_SETTINGS,
129
- ...(imageTag ? { KIOKU_TAG: imageTag } : {}),
130
- })
131
- if (imageTag) body = body.replace(/^KIOKU_TAG=/m, `${tagNote(imageTag)}\nKIOKU_TAG=`)
132
- try {
133
- // wx:写的这一刻别人刚建了也不覆盖
134
- await writeFile(file, body, { mode: 0o600, flag: 'wx' })
135
- await chmod(file, 0o600)
136
- } catch (err) {
137
- if (err?.code === 'EEXIST') return writeEnvFile(dir, template, { random, imageTag })
138
- await rm(file, { force: true }).catch(() => {})
139
- throw new KiokuFailure(`无法写入 ${file}(${errorKind(err)})`)
140
- }
141
- return { written: true, file, setupCode: secrets.KIOKU_SETUP_CODE }
142
- }
143
-
144
- // 下载一个文件放进目录;已有的不覆盖,返回 'kept',下载了返回 'downloaded'。失败时抛 KiokuFailure
145
- export async function download(url, file, { fetchImpl = fetch } = {}) {
146
- if (
147
- await readFile(file).then(
148
- () => true,
149
- () => false,
150
- )
151
- )
152
- return 'kept'
153
- let text
154
- try {
155
- const res = await fetchImpl(url, { signal: AbortSignal.timeout(20_000) })
156
- if (!res.ok) throw new KiokuFailure(`下载 ${url} 失败(HTTP ${res.status})`)
157
- text = await res.text()
158
- } catch (err) {
159
- if (err instanceof KiokuFailure) throw err
160
- throw new KiokuFailure(`下载 ${url} 失败(${networkReason(err)})`)
161
- }
162
- try {
163
- await writeFile(file, text, { flag: 'wx' })
164
- } catch (err) {
165
- if (err?.code === 'EEXIST') return 'kept'
166
- throw new KiokuFailure(`无法写入 ${file}(${errorKind(err)})`)
167
- }
168
- return 'downloaded'
169
- }
170
-
171
- // 下载失败时让用户自己运行的命令
172
- export function manualDownload(dir, ref = 'main') {
173
- return [
174
- `mkdir -p ${dir} && cd ${dir}`,
175
- `curl -fsSLO ${rawUrl(ref, 'compose.yaml')}`,
176
- `curl -fsSL -o .env.example ${rawUrl(ref, '.env.example')}`,
177
- ].join('\n')
178
- }
179
-
180
- // 准备目录:建目录、从 release.ref 下载 compose.yaml 与 .env.example、生成 .env(镜像固定在 release.imageTag)。
181
- // 返回 { files, env }
182
- export async function prepareDir(dir, release, { fetchImpl, random } = {}) {
183
- try {
184
- await mkdir(dir, { recursive: true })
185
- } catch (err) {
186
- throw new KiokuFailure(`无法创建目录 ${dir}(${errorKind(err)})`)
187
- }
188
- const fetchFile = (name, file) => download(rawUrl(release.ref, name), file, { fetchImpl })
189
- const compose = await fetchFile('compose.yaml', join(dir, 'compose.yaml'))
190
- const example = await fetchFile('.env.example', join(dir, '.env.example'))
191
- const template = await readFile(join(dir, '.env.example'), 'utf8')
192
- const env = await writeEnvFile(dir, template, { random, imageTag: release.imageTag })
193
- return { files: { compose, example }, env }
194
- }
195
-
196
- // 这个目录里的 .env 写的初始化码;没有为 null
197
- export async function setupCodeIn(dir) {
198
- const text = await readFile(join(dir, '.env'), 'utf8').catch(() => null)
199
- return (text && envValue(text, 'KIOKU_SETUP_CODE')) || null
200
- }
201
-
202
- // 这个目录的 compose 项目里有没有 kioku 服务:'none'(没有 compose.yaml,或者没建过容器)、
203
- // 'stopped'(建过、没在运行)、'running'。查不了的按 'none' 算
204
- export async function composeState(dir, env) {
205
- if (!(await stat(join(dir, 'compose.yaml')).catch(() => null))) return 'none'
206
- const base = ['compose', '-f', join(dir, 'compose.yaml'), '--project-directory', dir, 'ps']
207
- const services = async (args) => {
208
- const result = await capture('docker', [...base, ...args], env, { timeout: 30_000 })
209
- return result.found && result.ok ? result.stdout.split(/\r?\n/).map((line) => line.trim()) : []
210
- }
211
- if (!(await services(['-a', '--services'])).includes('kioku')) return 'none'
212
- return (await services(['--services', '--status', 'running'])).includes('kioku')
213
- ? 'running'
214
- : 'stopped'
215
- }
216
-
217
- // docker compose 能不能用
218
- export async function hasCompose(env) {
219
- const result = await capture('docker', ['compose', 'version'], env, { timeout: 20_000 })
220
- return Boolean(result.found && result.ok)
221
- }
222
-
223
- // 端口有没有被别的程序占着:连得上,或者绑不上。只试绑 127.0.0.1 不够:别的程序听着 [::] 或 0.0.0.0 时
224
- // 有的系统照样让绑更具体的地址
225
- export async function portBusy(port, host = '127.0.0.1') {
226
- const answers = await new Promise((done) => {
227
- const socket = connect({ port, host })
228
- socket.setTimeout(1000)
229
- const finish = (value) => {
230
- socket.destroy()
231
- done(value)
232
- }
233
- socket.once('connect', () => finish(true))
234
- socket.once('timeout', () => finish(false))
235
- socket.once('error', () => finish(false))
236
- })
237
- if (answers) return true
238
- return new Promise((done) => {
239
- const server = createServer()
240
- server.once('error', (err) => done(err?.code === 'EADDRINUSE'))
241
- server.once('listening', () => server.close(() => done(false)))
242
- server.listen(port, host)
243
- })
244
- }
245
-
246
- // docker compose up -d:用这个目录的 compose.yaml 与 .env。失败时抛 KiokuFailure,输出只取最后几行
247
- export async function composeUp(dir, env) {
248
- const result = await capture(
249
- 'docker',
250
- ['compose', '-f', join(dir, 'compose.yaml'), '--project-directory', dir, 'up', '-d'],
251
- env,
252
- { timeout: 30 * 60_000 },
253
- )
254
- if (!result.found) throw new KiokuFailure('没有找到 docker 命令')
255
- if (!result.ok) {
256
- const tail = result.output.trim().split(/\r?\n/).slice(-5).join('\n')
257
- throw new KiokuFailure(`docker compose up 没有成功:\n${tail}`)
258
- }
259
- }
260
-
261
- // 轮询直到 check 返回真,或者到时限;返回有没有等到
262
- export async function waitUntil(
263
- check,
264
- { timeoutMs, intervalMs = 2000, sleep, now = () => Date.now() },
265
- ) {
266
- const pause = sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)))
267
- const deadline = now() + timeoutMs
268
- while (now() < deadline) {
269
- if (await check().catch(() => false)) return true
270
- await pause(intervalMs)
271
- }
272
- return false
273
- }
274
-
275
- // /v1/health 回 200
276
- export async function healthy(url) {
277
- try {
278
- const res = await fetch(`${url}/v1/health`, { signal: AbortSignal.timeout(3000) })
279
- return res.status === 200
280
- } catch {
281
- return false
282
- }
283
- }
284
-
285
- // 第一个管理员建好了没有(/v1/setup/status 的 needsSetup 变成 false)
286
- export async function setupDone(url) {
287
- try {
288
- const res = await fetch(`${url}/v1/setup/status`, { signal: AbortSignal.timeout(3000) })
289
- const data = await res.json()
290
- return res.status === 200 && data?.needsSetup === false
291
- } catch {
292
- return false
293
- }
294
- }
package/lib/login.mjs DELETED
@@ -1,347 +0,0 @@
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 { configure, orphanHint } from './connect.mjs'
10
- import { fetchFailure, isRedirect, KiokuFailure, redirectError } from './http.mjs'
11
- import { platformNames, PLATFORMS } from './platforms.mjs'
12
- import { resolveServerUrl } from './target.mjs'
13
- import { plain } from './text.mjs'
14
- import { UsageError } from './usage.mjs'
15
-
16
- export const LOGIN_USAGE = `用法:kioku login <平台> [--server-url <地址>] [--no-browser]
17
-
18
- 用浏览器授权给这个平台签发一个访问密钥并配好,不用手动复制:终端显示一个确认码,
19
- 在 Kioku 管理界面的确认页输入它,选好空间与权限后确认。
20
-
21
- <平台> ${platformNames()}(Claude Code 的访问密钥在它的 /plugin 里填,不走这里)
22
- --server-url <地址> Kioku 的服务地址,例如 https://kioku.example.com(也可以用 KIOKU_SERVER_URL;配过的沿用上次的)
23
- --no-browser 不自动打开浏览器,只显示地址
24
-
25
- 只在自己刚运行了这条命令时确认:确认之后,这台机器会拿到一个能按所选权限读写记忆的访问密钥。
26
- `
27
-
28
- const TIMEOUT = 8000
29
- // 连着这么多次没得到回答(连不上、服务端 5xx)才放弃:等确认的这几分钟里抖一下不算失败
30
- const MAX_FAILURES = 5
31
- // 确认页的路径只收这种写法:接在服务地址后面打开,不带查询参数与别的符号
32
- const VERIFICATION_PATH = /^\/[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*$/
33
- // 服务端给的时限与间隔收在这个范围里(秒):给得再离谱也不会一直等、不会忙等
34
- const MAX_EXPIRES = 1800
35
- const MIN_INTERVAL = 1
36
- const MAX_INTERVAL = 60
37
-
38
- // 地址返回了跳转:配置的问题,重试没有用
39
- class Redirected extends KiokuFailure {}
40
-
41
- // 取走访问密钥这一步之后出的问题:访问密钥可能已经签发、却没有落到这台机器上
42
- const ORPHAN_HINT =
43
- '如果确认页上已经点了确认,可能已经签发了一个没被取走的访问密钥:到管理界面的应用页吊销它,再重新运行'
44
-
45
- async function post(url, path, body) {
46
- let res
47
- let data
48
- try {
49
- res = await fetch(`${url}${path}`, {
50
- method: 'POST',
51
- headers: { 'content-type': 'application/json' },
52
- body: JSON.stringify(body),
53
- // 不跟着跳转走:设备码只发给配置的地址
54
- redirect: 'manual',
55
- signal: AbortSignal.timeout(TIMEOUT),
56
- })
57
- data = await res.json().catch(() => null)
58
- } catch (err) {
59
- throw new KiokuFailure(fetchFailure(err, TIMEOUT))
60
- }
61
- if (isRedirect(res.status)) {
62
- throw new Redirected(redirectError(res.status, res.headers.get('location'), url))
63
- }
64
- return { status: res.status, data }
65
- }
66
-
67
- // 服务端给的秒数收进范围;不是有限的正数时用默认值
68
- function seconds(value, fallback, min, max) {
69
- const number = typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : fallback
70
- return Math.min(max, Math.max(min, number))
71
- }
72
-
73
- // 服务端不认一次申请几个平台的写法:退回逐个平台申请
74
- export class LegacyServer extends KiokuFailure {}
75
-
76
- // 旧的服务端只认单个平台的写法,收到 platforms 时按校验失败回 400,第一条问题是缺 runtimeFamily
77
- // (「runtimeFamily:…」)。别的 400 是申请本身有问题,照原样报
78
- function legacyRejection(data) {
79
- return typeof data?.error === 'string' && /^runtimeFamily[::]/.test(data.error)
80
- }
81
-
82
- // 一次申请最多几个平台,与服务端的上限一致
83
- export const MAX_PLATFORMS = 8
84
-
85
- // 申请:返回设备码、确认码、确认页的地址与时限。body 是单平台的 { runtimeFamily, clientName },
86
- // 或几个平台的 { platforms: [{ runtimeFamily }], clientName }
87
- export async function requestGrant(url, body) {
88
- const { clientName, ...rest } = body
89
- const { status, data } = await post(url, '/v1/device/authorize', {
90
- ...rest,
91
- ...(clientName ? { clientName } : {}),
92
- })
93
- if (status === 400 && Array.isArray(body.platforms) && legacyRejection(data)) {
94
- throw new LegacyServer('服务端版本较旧,需要逐个确认')
95
- }
96
- if (status === 400) {
97
- const reason = typeof data?.error === 'string' ? plain(data.error) : ''
98
- throw new KiokuFailure(`Kioku 拒绝了这次申请${reason ? `:${reason}` : ''}`)
99
- }
100
- if (status === 404) {
101
- throw new KiokuFailure(
102
- '这个 Kioku 还不支持浏览器授权:升级服务端,或者用 kioku setup 手动填访问密钥',
103
- )
104
- }
105
- if (status === 429) throw new KiokuFailure('待确认的申请太多,稍后再试')
106
- if (status !== 201) throw new KiokuFailure(`Kioku 返回 HTTP ${status}`)
107
- if (
108
- typeof data?.deviceCode !== 'string' ||
109
- !data.deviceCode ||
110
- typeof data.userCode !== 'string' ||
111
- typeof data.verificationPath !== 'string' ||
112
- !VERIFICATION_PATH.test(data.verificationPath)
113
- ) {
114
- throw new KiokuFailure('Kioku 的响应格式不对')
115
- }
116
- return {
117
- deviceCode: data.deviceCode,
118
- userCode: data.userCode,
119
- verificationUrl: `${url}${data.verificationPath}`,
120
- expiresIn: seconds(data.expiresIn, 600, 1, MAX_EXPIRES),
121
- interval: seconds(data.interval, 3, MIN_INTERVAL, MAX_INTERVAL),
122
- }
123
- }
124
-
125
- // 等确认:按服务端给的间隔轮询,确认了返回服务端的整个回答;被拒绝、过期时抛 KiokuFailure。
126
- // sleep 与 now 可以换掉,给用例用;now 要是只往前走的钟,系统时间被改不影响什么时候停
127
- async function waitForApproval(
128
- url,
129
- grant,
130
- {
131
- sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
132
- now = () => performance.now(),
133
- } = {},
134
- ) {
135
- const deadline = now() + grant.expiresIn * 1000
136
- let interval = grant.interval * 1000
137
- let failures = 0
138
- // 有过没得到回答的轮询:那一次服务端可能已经把访问密钥签出来了
139
- let missed = false
140
- while (now() < deadline) {
141
- await sleep(interval)
142
- let answer
143
- try {
144
- answer = await post(url, '/v1/device/token', { deviceCode: grant.deviceCode })
145
- } catch (err) {
146
- if (err instanceof Redirected) throw err
147
- missed = true
148
- if (++failures >= MAX_FAILURES) throw new KiokuFailure(`${err.message}。${ORPHAN_HINT}`)
149
- continue
150
- }
151
- const { status, data } = answer
152
- // 服务端嫌太勤:隔久一点
153
- if (status === 429) {
154
- interval = Math.min(interval + 1000, MAX_INTERVAL * 1000)
155
- continue
156
- }
157
- // 服务端一时出错(重启、网关)和连不上一样,过会儿再问
158
- if (status >= 500) {
159
- missed = true
160
- if (++failures >= MAX_FAILURES) {
161
- throw new KiokuFailure(`Kioku 返回 HTTP ${status}。${ORPHAN_HINT}`)
162
- }
163
- continue
164
- }
165
- if (status !== 200) throw new KiokuFailure(`Kioku 返回 HTTP ${status}`)
166
- failures = 0
167
- if (data?.status === 'pending') continue
168
- if (data?.status === 'denied') {
169
- throw new KiokuFailure('申请被拒绝了,或者确认之后确认人的权限变了:没有签发访问密钥')
170
- }
171
- if (data?.status === 'approved') return data
172
- if (data?.status === 'expired') break
173
- throw new KiokuFailure('Kioku 的响应格式不对')
174
- }
175
- throw new KiokuFailure(
176
- missed
177
- ? `申请已经不在了,没有取到访问密钥。${ORPHAN_HINT}`
178
- : '申请过期了,没有等到确认:重新运行 kioku login',
179
- )
180
- }
181
-
182
- // 等一个平台的申请被确认,返回访问密钥与应用
183
- export async function waitForKey(url, grant, options) {
184
- const data = await waitForApproval(url, grant, options)
185
- if (typeof data.key !== 'string' || !data.key) throw new KiokuFailure('Kioku 的响应格式不对')
186
- return { key: data.key, app: data.app ?? {} }
187
- }
188
-
189
- // 几个平台一起的申请被确认之后,每个平台的结果:按申请的顺序,
190
- // { runtimeFamily, status: 'issued', key, app } | { runtimeFamily, status: 'skipped' } | { runtimeFamily, status: 'denied', reason }。
191
- // 服务端没提到的平台算跳过,不认识的平台、重复的项不收;签发了却不像访问密钥的算响应不对
192
- export async function waitForKeys(url, grant, families, options) {
193
- const data = await waitForApproval(url, grant, options)
194
- // 已经确认了:响应读不懂时,服务端可能已经签发了几个没人拿着的访问密钥
195
- const malformed = () => new KiokuFailure(`Kioku 的响应格式不对。${ORPHAN_HINT}`)
196
- if (!Array.isArray(data.keys)) throw malformed()
197
- const byFamily = new Map()
198
- for (const item of data.keys) {
199
- const family = item?.runtimeFamily
200
- if (!families.includes(family) || byFamily.has(family)) continue
201
- if (item.status === 'issued') {
202
- if (typeof item.key !== 'string' || !item.key) throw malformed()
203
- byFamily.set(family, {
204
- runtimeFamily: family,
205
- status: 'issued',
206
- key: item.key,
207
- app: item.app ?? {},
208
- })
209
- } else if (item.status === 'denied') {
210
- const reason = typeof item.reason === 'string' ? plain(item.reason) : ''
211
- byFamily.set(family, { runtimeFamily: family, status: 'denied', reason })
212
- } else byFamily.set(family, { runtimeFamily: family, status: 'skipped' })
213
- }
214
- return families.map(
215
- (family) => byFamily.get(family) ?? { runtimeFamily: family, status: 'skipped' },
216
- )
217
- }
218
-
219
- // 用系统默认的浏览器打开地址;打不开就算了,地址已经显示在终端里。都不经过 shell:
220
- // Windows 上用 rundll32,不用 cmd 的 start(它会把地址里的 & 这类符号当成命令)
221
- export function openBrowser(address) {
222
- const [command, args] =
223
- process.platform === 'darwin'
224
- ? ['open', [address]]
225
- : process.platform === 'win32'
226
- ? ['rundll32', ['url.dll,FileProtocolHandler', address]]
227
- : ['xdg-open', [address]]
228
- try {
229
- const child = spawn(command, args, { stdio: 'ignore', detached: true })
230
- child.on('error', () => {})
231
- child.unref()
232
- } catch {
233
- // 没有图形界面
234
- }
235
- }
236
-
237
- // 本地网络给主机名加的后缀,不算机器的名字
238
- const HOST_SUFFIX = /\.(?:local|localdomain|lan|home|internal)$/i
239
-
240
- // 机器名是自报的:去掉控制字符与 .local 这类后缀,太长就截断;什么都不剩时用 kioku-cli。
241
- // 服务端把它显示在确认页上,新建的应用默认叫「平台名 · 机器名」
242
- export function machineName(clientName) {
243
- const name = Array.from(plain(clientName).replace(HOST_SUFFIX, '').trim())
244
- .slice(0, 64)
245
- .join('')
246
- .trim()
247
- return name || 'kioku-cli'
248
- }
249
-
250
- // 显示确认码与确认页,打开浏览器
251
- function showGrant(grant, { out, open, browser }) {
252
- out.write(`确认码:${plain(grant.userCode)}\n`)
253
- // 显示的和打开的是同一个地址
254
- out.write(`在浏览器里打开 ${plain(grant.verificationUrl)},登录后输入这个确认码\n`)
255
- out.write(`等待确认(${Math.ceil(grant.expiresIn / 60)} 分钟内有效)…\n`)
256
- if (browser) open(grant.verificationUrl)
257
- }
258
-
259
- // 走一遍浏览器授权,返回访问密钥。提示写到 out,访问密钥不写
260
- export async function deviceLogin(
261
- { url, runtimeFamily },
262
- { out, open = openBrowser, browser = true, clientName = hostname(), sleep, now } = {},
263
- ) {
264
- const grant = await requestGrant(url, { runtimeFamily, clientName: machineName(clientName) })
265
- showGrant(grant, { out, open, browser })
266
- const { key, app } = await waitForKey(url, grant, { sleep, now })
267
- out.write(`✓ 已确认:应用 ${plain(app.name ?? '')}(${plain(app.slug ?? '')})\n`)
268
- return key
269
- }
270
-
271
- // 几个平台一起申请,只确认一次。返回 waitForKeys 的结果(按去重后的顺序);服务端不认这种写法时抛 LegacyServer。
272
- // 一次最多 MAX_PLATFORMS 个,多了由调用方分批(connect.mjs),这里不发超出上限的申请
273
- export async function deviceLoginMany(
274
- { url, runtimeFamilies },
275
- { out, open = openBrowser, browser = true, clientName = hostname(), sleep, now } = {},
276
- ) {
277
- const families = [...new Set(runtimeFamilies)]
278
- if (!families.length || families.length > MAX_PLATFORMS) {
279
- throw new KiokuFailure(`一次申请 1 到 ${MAX_PLATFORMS} 个平台`)
280
- }
281
- const grant = await requestGrant(url, {
282
- platforms: families.map((runtimeFamily) => ({ runtimeFamily })),
283
- clientName: machineName(clientName),
284
- })
285
- showGrant(grant, { out, open, browser })
286
- const results = await waitForKeys(url, grant, families, { sleep, now })
287
- // 确认了也可能一个都没签发:取走时照签发规则再核对,全都没过(例如确认人已停用)
288
- const issued = results.filter((item) => item.status === 'issued').length
289
- out.write(issued ? `✓ 已确认,签发了 ${issued} 个访问密钥\n` : '✗ 已确认,但没有签发访问密钥\n')
290
- return results
291
- }
292
-
293
- export function parseLoginArgs(argv) {
294
- const options = { serverUrl: undefined, browser: true }
295
- const names = []
296
- for (let i = 0; i < argv.length; i++) {
297
- const arg = argv[i]
298
- if (arg === '--no-browser') options.browser = false
299
- else if (arg === '--server-url') {
300
- options.serverUrl = argv[++i]
301
- if (!options.serverUrl) throw new UsageError('--server-url 后面要写地址')
302
- } else if (arg.startsWith('-')) throw new UsageError(`不认识的选项 ${arg}`)
303
- else names.push(arg)
304
- }
305
- if (names.length !== 1) throw new UsageError('要写一个平台')
306
- if (!Object.hasOwn(PLATFORMS, names[0])) {
307
- throw new UsageError(`不认识的平台 ${names[0]},可以用的:${platformNames()}`)
308
- }
309
- if (!PLATFORMS[names[0]].setup) {
310
- throw new UsageError(
311
- `${PLATFORMS[names[0]].name} 的访问密钥在它自己的插件配置里填,不走 kioku login`,
312
- )
313
- }
314
- return { ...options, platform: names[0] }
315
- }
316
-
317
- export async function login(
318
- argv,
319
- {
320
- env = process.env,
321
- out = process.stdout,
322
- cwd = process.cwd(),
323
- open,
324
- sleep,
325
- now,
326
- clientName,
327
- } = {},
328
- ) {
329
- const options = parseLoginArgs(argv)
330
- const platform = PLATFORMS[options.platform]
331
- const saved = await Promise.resolve(platform.readConfig?.(env)).catch(() => null)
332
- const url = resolveServerUrl(options, env, saved)
333
- // 申请之前先看这个平台的配置写不写得进去:访问密钥只在签发时给一次
334
- await platform.preflight?.({ env, cwd })
335
- const key = await deviceLogin(
336
- { url, runtimeFamily: platform.runtimeFamily },
337
- { out, open, browser: options.browser, sleep, now, ...(clientName ? { clientName } : {}) },
338
- )
339
- // 拿到的访问密钥交给这个平台的 setup:核对、写文件都照它的规矩
340
- try {
341
- return await configure(options.platform, { url, key }, { env, out, cwd }, { hints: true })
342
- } catch (err) {
343
- if (!(err instanceof KiokuFailure)) throw err
344
- // 访问密钥已经签发、却没有写下来:说清楚,别让它悄悄留着
345
- throw new KiokuFailure(`${err.message}。${orphanHint()}`)
346
- }
347
- }