@kioku-memory/cli 0.1.0 → 0.2.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/kioku.mjs CHANGED
@@ -10,6 +10,7 @@ import { isatty } from 'node:tty'
10
10
  import { killTree, launch } from './command.mjs'
11
11
  import { loadConfig } from './config.mjs'
12
12
  import { IMPORT_USAGE, importMemories } from './import.mjs'
13
+ import { install, INSTALL_USAGE } from './install.mjs'
13
14
  import { login, LOGIN_USAGE } from './login.mjs'
14
15
  import { doctor, DOCTOR_USAGE } from './doctor.mjs'
15
16
  import {
@@ -20,6 +21,7 @@ import {
20
21
  KiokuFailure,
21
22
  redirectError,
22
23
  } from './http.mjs'
24
+ import { loadPrompts } from './prompts.mjs'
23
25
  import { setup, SETUP_USAGE } from './setup.mjs'
24
26
  import { UsageError } from './usage.mjs'
25
27
  import { createRedactor, MIN_REDACT_CHARS, redactable } from './redact.mjs'
@@ -378,15 +380,31 @@ async function run(argv) {
378
380
  // 入口:返回退出码
379
381
  const OVERVIEW = `用法:kioku <子命令> [参数…]
380
382
 
381
- run 向 Kioku 取凭据的值,放进环境变量交给命令
382
- login 用浏览器授权签发访问密钥并配好这个平台
383
- setup 停用平台自带的长期记忆,由 Kioku 接管
384
- doctor 检查地址、访问密钥与平台的配置
385
- import 把平台自带的本地长期记忆迁进 Kioku
383
+ run 向 Kioku 取凭据的值,放进环境变量交给命令
384
+ login 用浏览器授权签发访问密钥并配好这个平台
385
+ setup 停用平台自带的长期记忆,由 Kioku 接管
386
+ install 几个平台一起接入,访问密钥从环境变量读(给脚本用)
387
+ doctor 检查地址、访问密钥与平台的配置
388
+ import 把平台自带的本地长期记忆迁进 Kioku
386
389
 
390
+ 在终端里不带参数运行 kioku 是交互式的向导:看各平台接到哪一步,按缺的一步步接上。
387
391
  各子命令的说明:kioku <子命令> --help
388
392
  `
389
393
 
394
+ const NO_WIZARD =
395
+ '交互式的向导要 npm 上的 kioku(Node 20.12 以上):npm install -g @kioku-memory/cli\n'
396
+
397
+ // 交互式的向导。插件目录里的 kioku 带不了交互库,装不到时打印用法并说明
398
+ async function startWizard() {
399
+ const ui = await loadPrompts()
400
+ if (!ui) {
401
+ process.stderr.write(`${OVERVIEW}\n${NO_WIZARD}`)
402
+ return 2
403
+ }
404
+ const { barOut, wizard } = await import('./wizard.mjs')
405
+ return wizard({ ui, env: process.env, cwd: process.cwd(), out: barOut(process.stdout) })
406
+ }
407
+
390
408
  // 说明类的子命令:参数写错时打印原因与说明,以 2 退出;别的失败原因写到标准错误
391
409
  async function guarded(name, usage, fn, argv) {
392
410
  if (argv.includes('-h') || argv.includes('--help')) {
@@ -408,8 +426,13 @@ async function guarded(name, usage, fn, argv) {
408
426
  }
409
427
  }
410
428
 
411
- export async function main(argv) {
429
+ // interactive:标准输入与输出都是终端时才进向导;管道、agent 的命令里照旧打印用法
430
+ export async function main(
431
+ argv,
432
+ { interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY), wizard = startWizard } = {},
433
+ ) {
412
434
  const [sub, ...rest] = argv
435
+ if (sub === undefined && interactive) return wizard()
413
436
  if (sub === '-h' || sub === '--help') {
414
437
  process.stdout.write(OVERVIEW)
415
438
  return 0
@@ -417,6 +440,7 @@ export async function main(argv) {
417
440
  if (sub === 'run') return run(rest)
418
441
  if (sub === 'login') return guarded('login', LOGIN_USAGE, login, rest)
419
442
  if (sub === 'setup') return guarded('setup', SETUP_USAGE, setup, rest)
443
+ if (sub === 'install') return guarded('install', INSTALL_USAGE, install, rest)
420
444
  if (sub === 'doctor') return guarded('doctor', DOCTOR_USAGE, doctor, rest)
421
445
  if (sub === 'import') return guarded('import', IMPORT_USAGE, importMemories, rest)
422
446
  process.stderr.write(sub === undefined ? OVERVIEW : `kioku:不认识的子命令 ${sub}\n\n${OVERVIEW}`)
package/lib/local.mjs ADDED
@@ -0,0 +1,294 @@
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 CHANGED
@@ -6,6 +6,7 @@
6
6
  import { spawn } from 'node:child_process'
7
7
  import { hostname } from 'node:os'
8
8
 
9
+ import { configure, orphanHint } from './connect.mjs'
9
10
  import { fetchFailure, isRedirect, KiokuFailure, redirectError } from './http.mjs'
10
11
  import { platformNames, PLATFORMS } from './platforms.mjs'
11
12
  import { resolveServerUrl } from './target.mjs'
@@ -69,12 +70,33 @@ function seconds(value, fallback, min, max) {
69
70
  return Math.min(max, Math.max(min, number))
70
71
  }
71
72
 
72
- // 申请:返回设备码、确认码、确认页的地址与时限
73
- export async function requestGrant(url, { runtimeFamily, clientName }) {
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
74
89
  const { status, data } = await post(url, '/v1/device/authorize', {
75
- runtimeFamily,
90
+ ...rest,
76
91
  ...(clientName ? { clientName } : {}),
77
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
+ }
78
100
  if (status === 404) {
79
101
  throw new KiokuFailure(
80
102
  '这个 Kioku 还不支持浏览器授权:升级服务端,或者用 kioku setup 手动填访问密钥',
@@ -100,9 +122,9 @@ export async function requestGrant(url, { runtimeFamily, clientName }) {
100
122
  }
101
123
  }
102
124
 
103
- // 等确认:按服务端给的间隔轮询,返回访问密钥与应用;被拒绝、过期时抛 KiokuFailure。
125
+ // 等确认:按服务端给的间隔轮询,确认了返回服务端的整个回答;被拒绝、过期时抛 KiokuFailure。
104
126
  // sleep 与 now 可以换掉,给用例用;now 要是只往前走的钟,系统时间被改不影响什么时候停
105
- export async function waitForKey(
127
+ async function waitForApproval(
106
128
  url,
107
129
  grant,
108
130
  {
@@ -146,9 +168,7 @@ export async function waitForKey(
146
168
  if (data?.status === 'denied') {
147
169
  throw new KiokuFailure('申请被拒绝了,或者确认之后确认人的权限变了:没有签发访问密钥')
148
170
  }
149
- if (data?.status === 'approved' && typeof data.key === 'string' && data.key) {
150
- return { key: data.key, app: data.app ?? {} }
151
- }
171
+ if (data?.status === 'approved') return data
152
172
  if (data?.status === 'expired') break
153
173
  throw new KiokuFailure('Kioku 的响应格式不对')
154
174
  }
@@ -159,9 +179,46 @@ export async function waitForKey(
159
179
  )
160
180
  }
161
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
+
162
219
  // 用系统默认的浏览器打开地址;打不开就算了,地址已经显示在终端里。都不经过 shell:
163
220
  // Windows 上用 rundll32,不用 cmd 的 start(它会把地址里的 & 这类符号当成命令)
164
- function openBrowser(address) {
221
+ export function openBrowser(address) {
165
222
  const [command, args] =
166
223
  process.platform === 'darwin'
167
224
  ? ['open', [address]]
@@ -177,24 +234,62 @@ function openBrowser(address) {
177
234
  }
178
235
  }
179
236
 
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 })
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 }) {
188
252
  out.write(`确认码:${plain(grant.userCode)}\n`)
189
253
  // 显示的和打开的是同一个地址
190
254
  out.write(`在浏览器里打开 ${plain(grant.verificationUrl)},登录后输入这个确认码\n`)
191
255
  out.write(`等待确认(${Math.ceil(grant.expiresIn / 60)} 分钟内有效)…\n`)
192
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 })
193
266
  const { key, app } = await waitForKey(url, grant, { sleep, now })
194
267
  out.write(`✓ 已确认:应用 ${plain(app.name ?? '')}(${plain(app.slug ?? '')})\n`)
195
268
  return key
196
269
  }
197
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
+
198
293
  export function parseLoginArgs(argv) {
199
294
  const options = { serverUrl: undefined, browser: true }
200
295
  const names = []
@@ -243,15 +338,10 @@ export async function login(
243
338
  )
244
339
  // 拿到的访问密钥交给这个平台的 setup:核对、写文件都照它的规矩
245
340
  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
- )
341
+ return await configure(options.platform, { url, key }, { env, out, cwd }, { hints: true })
250
342
  } catch (err) {
251
343
  if (!(err instanceof KiokuFailure)) throw err
252
344
  // 访问密钥已经签发、却没有写下来:说清楚,别让它悄悄留着
253
- throw new KiokuFailure(
254
- `${err.message}。访问密钥已经签发、但没有写下:到管理界面的应用页吊销它,解决上面的问题后重新运行`,
255
- )
345
+ throw new KiokuFailure(`${err.message}。${orphanHint()}`)
256
346
  }
257
347
  }
package/lib/openclaw.mjs CHANGED
@@ -201,7 +201,7 @@ export async function setupOpenclaw(options, io) {
201
201
  out.write(
202
202
  '插件装了没有、记忆槽位选的是什么没有查出来(openclaw plugins inspect 失败了):用 kioku doctor openclaw 再看一次\n',
203
203
  )
204
- } else if (!state) {
204
+ } else if (!state && io.hints !== false) {
205
205
  out.write(`接下来装上插件:openclaw plugins install ${SOURCE}\n`)
206
206
  if (todo.length) out.write('装好之后再运行一次 kioku setup openclaw。\n')
207
207
  }
@@ -246,3 +246,11 @@ export async function inspectOpenclaw({ env }, { ok, warn, note }) {
246
246
  '工作区里的 MEMORY.md 有内容时 OpenClaw 仍会放进提示:用 kioku import --from openclaw 迁走后清空它',
247
247
  )
248
248
  }
249
+
250
+ // 给向导的面板:插件装没装、记忆槽位选的是不是 kioku。没有 openclaw 命令、没查出来时为 null
251
+ export async function statusOpenclaw({ env }) {
252
+ const state = await pluginState(env)
253
+ if (state === null || state === undefined) return { plugin: null, memory: null }
254
+ if (!state) return { plugin: false, memory: 'on' }
255
+ return { plugin: state.enabled && state.loaded, memory: state.slot ? 'off' : 'on' }
256
+ }