@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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kioku-memory/cli",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "Kioku 的命令行:接入各平台的向导、把凭据交给命令(kioku run)、停用各平台自带的长期记忆(kioku setup)、检查配置(kioku doctor)",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://github.com/lonelyman0108/kioku-plugins/tree/main/packages/cli",
@@ -19,14 +19,23 @@
19
19
  },
20
20
  "files": [
21
21
  "bin",
22
- "lib",
22
+ "dist",
23
+ "assets",
23
24
  "NOTICE"
24
25
  ],
25
- "dependencies": {
26
- "@clack/prompts": "1.9.0"
26
+ "scripts": {
27
+ "build": "node scripts/build.mjs",
28
+ "typecheck": "tsc -p tsconfig.json",
29
+ "test": "pnpm run build && vitest run"
30
+ },
31
+ "devDependencies": {
32
+ "@types/node": "26.6.5",
33
+ "tsdown": "0.23.2",
34
+ "typescript": "6.0.3",
35
+ "vitest": "5.0.5"
27
36
  },
28
37
  "engines": {
29
- "node": ">=18"
38
+ "node": ">=22.12.0"
30
39
  },
31
40
  "publishConfig": {
32
41
  "access": "public"
package/lib/api.mjs DELETED
@@ -1,38 +0,0 @@
1
- // kioku 命令向 Kioku 发的核对请求
2
-
3
- import { fetchFailure, isRedirect, KiokuFailure, redirectError } from './http.mjs'
4
-
5
- const TIMEOUT = 8000
6
-
7
- // 服务端明说访问密钥不能用(401):和连不上、响应不对分开,向导据此标「已失效」
8
- export class KeyRejected extends KiokuFailure {}
9
-
10
- // 这个访问密钥对应的应用与权限;连不上、跳转、访问密钥无效、响应不对都以 KiokuFailure 抛出
11
- export async function whoami({ url, key }) {
12
- let res
13
- let data
14
- try {
15
- res = await fetch(`${url}/v1/whoami`, {
16
- headers: { authorization: `Bearer ${key}` },
17
- // 不跟着跳转走:访问密钥只发给配置的地址
18
- redirect: 'manual',
19
- signal: AbortSignal.timeout(TIMEOUT),
20
- })
21
- data = await res.json().catch(() => null)
22
- } catch (err) {
23
- throw new KiokuFailure(fetchFailure(err, TIMEOUT))
24
- }
25
- if (isRedirect(res.status)) {
26
- throw new KiokuFailure(redirectError(res.status, res.headers.get('location'), url))
27
- }
28
- if (res.status === 401) throw new KeyRejected('访问密钥无效或已吊销')
29
- if (!res.ok) throw new KiokuFailure(`Kioku 返回 HTTP ${res.status}`)
30
- if (
31
- typeof data?.app?.runtimeFamily !== 'string' ||
32
- data.scopes === null ||
33
- typeof data.scopes !== 'object'
34
- ) {
35
- throw new KiokuFailure('Kioku 的响应格式不对')
36
- }
37
- return data
38
- }
package/lib/codex.mjs DELETED
@@ -1,320 +0,0 @@
1
- // Codex 这个平台的 kioku setup 与 kioku doctor。
2
- // Codex 的插件没有自己的配置项,MCP 服务的地址也只能写在用户的 config.toml 里,所以 setup 做三件事:
3
- // 把服务地址与访问密钥写进本机的文件(钩子读它)、在 config.toml 里加上 Kioku 的 MCP 服务、关掉 Codex 自带的 Memories。
4
- // config.toml 只按行改:不解析整份 TOML,只认段的标题与要改的那几行。名叫 kioku 的 MCP 服务
5
- // ([mcp_servers.kioku] 与它的子段)整个归 kioku setup 管。不用标记行圈范围:Codex 自己也会重写这个文件,
6
- // 注释会被它挪到别的段后面
7
-
8
- import { readdir, rm } from 'node:fs/promises'
9
- import { homedir } from 'node:os'
10
- import { join } from 'node:path'
11
-
12
- import { readText, safeWrite } from './files.mjs'
13
- import { KiokuFailure } from './http.mjs'
14
- import { profileDir, profileFile, readProfile, removeProfile, writeProfile } from './profile.mjs'
15
- import { resolveTarget } from './target.mjs'
16
- import { plain as plainText, shownUrl } from './text.mjs'
17
-
18
- const SERVER = 'mcp_servers.kioku'
19
- const MARKETPLACE = 'lonelyman0108/kioku-plugins'
20
-
21
- export function codexHome(env) {
22
- return env.CODEX_HOME || join(homedir(), '.codex')
23
- }
24
-
25
- // TOML 的基本字符串:反斜杠与双引号要转义。地址与访问密钥都只有可见的 ASCII 字符
26
- function quoted(value) {
27
- return `"${value.replaceAll('\\', '\\\\').replaceAll('"', '\\"')}"`
28
- }
29
-
30
- function unquoted(value) {
31
- return (value ?? '').replace(/\\(["\\])/g, '$1')
32
- }
33
-
34
- // 写进 config.toml 的那几行
35
- function blockOf({ url, key }) {
36
- return [
37
- `[${SERVER}]`,
38
- `url = ${quoted(`${url}/v1/mcp`)}`,
39
- '',
40
- `[${SERVER}.http_headers]`,
41
- `Authorization = ${quoted(`Bearer ${key}`)}`,
42
- ]
43
- }
44
-
45
- // 标题里的一段名字:不带引号的,或者带引号的
46
- const KEY_PART = String.raw`(?:[A-Za-z0-9_-]+|"[^"]*"|'[^']*')`
47
- const HEADER = new RegExp(
48
- String.raw`^\s*\[\[?\s*(${KEY_PART}(?:\s*\.\s*${KEY_PART})*)\s*\]\]?\s*(#.*)?$`,
49
- )
50
-
51
- // 段的标题:[a.b] 或 [[a.b]],返回里面的名字;不是标题时为 null。
52
- // 名字规整成一种写法再比:点两边的空白去掉,只含普通字符的那一段去掉引号
53
- function headerOf(line) {
54
- const name = HEADER.exec(line)?.[1]
55
- if (name === undefined) return null
56
- return name
57
- .replace(/\s*\.\s*/g, '.')
58
- .replace(/"([A-Za-z0-9_-]+)"|'([A-Za-z0-9_-]+)'/g, (_, a, b) => a ?? b)
59
- }
60
-
61
- // 这一行让没有合上的方括号多了几层:多行的数组里,单独成行的 [1, 2] 不是标题。引号里的不算
62
- function bracketDelta(line) {
63
- const bare = line.replace(/"(?:[^"\\]|\\.)*"|'[^']*'/g, '').replace(/#.*$/, '')
64
- return (bare.match(/\[/g)?.length ?? 0) - (bare.match(/\]/g)?.length ?? 0)
65
- }
66
-
67
- // 把 config.toml 按行读成要用的几样:
68
- // - owned:kioku 的 MCP 服务占了哪些行
69
- // - unsupported:这个服务用按行认不出范围的写法定义了(行内表、带点的键),不能再加一段同名的
70
- // - memories:Memories 的开关写在哪一行;memoriesUnknown:features 用认不出的写法写了
71
- // - plugin:kioku 插件启用没有
72
- export function scanConfig(text) {
73
- const eol = text?.includes('\r\n') ? '\r\n' : '\n'
74
- const lines = text ? text.split(/\r?\n/) : []
75
- const found = {
76
- eol,
77
- lines,
78
- owned: [],
79
- unsupported: false,
80
- memories: null,
81
- memoriesUnknown: false,
82
- plugin: false,
83
- }
84
- let section = ''
85
- let depth = 0
86
- lines.forEach((line, index) => {
87
- const header = depth === 0 ? headerOf(line) : null
88
- if (header !== null) section = header
89
- else depth = Math.max(0, depth + bracketDelta(line))
90
- if (section === SERVER || section.startsWith(`${SERVER}.`)) {
91
- found.owned.push(index)
92
- return
93
- }
94
- if (header !== null) return
95
- // 这个服务的别的写法:最前面的 mcp_servers.kioku…、mcp_servers = { kioku… },或者 [mcp_servers] 段里的 kioku
96
- const quotedName = String.raw`["']?kioku["']?`
97
- if (
98
- (section === '' &&
99
- new RegExp(String.raw`^\s*mcp_servers\s*(\.\s*${quotedName}\s*[.=]|=.*\bkioku\b)`).test(
100
- line,
101
- )) ||
102
- (section === 'mcp_servers' && new RegExp(String.raw`^\s*${quotedName}\s*[.=]`).test(line))
103
- ) {
104
- found.unsupported = true
105
- }
106
- // Memories 的开关:[features] 段里的 memories,或者写在最前面的 features.memories
107
- const name = String.raw`["']?memories["']?`
108
- const key =
109
- section === 'features' ? name : section === '' ? String.raw`features\s*\.\s*${name}` : null
110
- const flag = key && new RegExp(String.raw`^(\s*${key}\s*=\s*)(true|false)\b(.*)$`).exec(line)
111
- if (flag) found.memories = { index, value: flag[2] === 'true', parts: flag }
112
- // features 写成行内表时认不出里面的开关
113
- if (section === '' && /^\s*features\s*=/.test(line)) found.memoriesUnknown = true
114
- // 插件:[plugins."kioku@<市场>"] 段里的 enabled = true
115
- if (/^plugins\.["']kioku@[^"']+["']$/.test(section) && /^\s*enabled\s*=\s*true\b/.test(line)) {
116
- found.plugin = true
117
- }
118
- })
119
- // 这一段后面的空行与注释不算它的(注释多半是写给下一段的):去掉这一段时不连带去掉
120
- while (found.owned.length && /^\s*(#.*)?$/.test(lines[found.owned.at(-1)])) found.owned.pop()
121
- return found
122
- }
123
-
124
- // kioku 的 MCP 服务现在写的地址与访问密钥;没有这个服务时为 null,有但认不出写法的那一项为空
125
- export function blockValues(found) {
126
- if (!found.owned.length) return null
127
- const inside = found.owned.map((index) => found.lines[index]).join('\n')
128
- const url = /^\s*url\s*=\s*"((?:[^"\\]|\\.)*)"/m.exec(inside)?.[1]
129
- const key = /\bAuthorization\s*=\s*"Bearer ((?:[^"\\]|\\.)*)"/.exec(inside)?.[1]
130
- // rawUrl 是原样写着的地址,只用来显示
131
- return { url: unquoted(url).replace(/\/v1\/mcp$/, ''), key: unquoted(key), rawUrl: unquoted(url) }
132
- }
133
-
134
- // 新的全文:去掉 kioku 的 MCP 服务原来的那些行,把 block 加在最后(为 null 时只去掉;keep 为真时这一段原样留在原处),
135
- // memoriesOff 为真时把 Memories 关掉。别的行原样不动,只收拾去掉的地方两边多出来的空行
136
- function rewrite(found, block, { memoriesOff, keep = false }) {
137
- const owned = new Set(keep ? [] : found.owned)
138
- const lines = []
139
- found.lines.forEach((line, index) => {
140
- if (owned.has(index)) return
141
- // 去掉一段之后,它前后的空行并成一行
142
- if (line === '' && owned.has(index - 1) && (lines.at(-1) ?? '') === '') return
143
- if (memoriesOff && found.memories?.value && index === found.memories.index) {
144
- const [, head, , tail] = found.memories.parts
145
- lines.push(`${head}false${tail}`)
146
- } else lines.push(line)
147
- })
148
- if (!owned.size && !block) return lines.join(found.eol)
149
- // 文件以一个换行结尾,新的一段前面空一行
150
- while (lines.length && lines.at(-1) === '') lines.pop()
151
- if (block) lines.push(...(lines.length ? [''] : []), ...block)
152
- return lines.length ? `${lines.join(found.eol)}${found.eol}` : ''
153
- }
154
-
155
- // 现在的 config.toml 里有没有写着访问密钥:有的话不留备份,免得撤销、换访问密钥之后旧的还留在备份里
156
- function holdsKey(found) {
157
- return Boolean(blockValues(found)?.key)
158
- }
159
-
160
- // 记下的用户输入(钩子在每轮提交时写的):撤销时一起删掉
161
- async function removePendingTurns(env) {
162
- const dirs = [join(profileDir(env), 'codex-state')]
163
- const data = join(codexHome(env), 'plugins', 'data')
164
- for (const name of await readdir(data).catch(() => [])) {
165
- if (name.startsWith('kioku-')) dirs.push(join(data, name, 'turns'))
166
- }
167
- for (const dir of dirs) await rm(dir, { recursive: true, force: true }).catch(() => {})
168
- }
169
-
170
- // 地址只打印协议、主机与路径;解析不了的压成一行再打印
171
- function shown(url) {
172
- try {
173
- return shownUrl(url)
174
- } catch {
175
- return plainText(url)
176
- }
177
- }
178
-
179
- const NEXT_STEPS = `接下来在 Codex 这一边:
180
- 1. codex plugin marketplace add ${MARKETPLACE}
181
- 2. codex plugin add kioku@kioku
182
- 3. 打开 codex,在 /hooks 里信任 kioku 的三个钩子(没信任过的钩子不会运行)
183
- `
184
-
185
- async function undo({ dryRun }, { env, out }) {
186
- const file = join(codexHome(env), 'config.toml')
187
- const text = await readText(file)
188
- const found = scanConfig(text)
189
- const profile = profileFile('codex', env)
190
- if (!found.owned.length) out.write(`${file} 里没有 Kioku 的 MCP 服务,不用改\n`)
191
- else {
192
- out.write(`${file}\n ${SERVER}:去掉\n`)
193
- if (!dryRun) {
194
- // 现在的文件里写着访问密钥,不留备份
195
- await safeWrite(file, rewrite(found, null, { memoriesOff: false }), text, { backup: false })
196
- }
197
- }
198
- if (found.unsupported) {
199
- out.write(`${file} 里还有用别的写法定义的 kioku 服务,没有改动它,要手动去掉\n`)
200
- }
201
- if (dryRun) out.write(`${profile}:删掉\n没有写入(--dry-run)\n`)
202
- else {
203
- if (await removeProfile('codex', env)) out.write(`已删掉 ${profile}\n`)
204
- await removePendingTurns(env)
205
- }
206
- out.write('Codex 自带的 Memories 没有重新打开:要用的话运行 codex features enable memories\n')
207
- out.write('插件要另外卸载:codex plugin remove kioku@kioku\n')
208
- return 0
209
- }
210
-
211
- export async function setupCodex(options, io) {
212
- const { env, out } = io
213
- if (options.undo) return undo(options, io)
214
- const file = join(codexHome(env), 'config.toml')
215
- const text = await readText(file)
216
- const found = scanConfig(text)
217
-
218
- const refuseUnsupported = () => {
219
- if (!found.unsupported) return
220
- throw new KiokuFailure(
221
- `${file} 里已经用行内表或带点的键定义了 kioku 这个 MCP 服务,没有改动它:删掉那个定义后重新运行`,
222
- )
223
- }
224
- // 要走浏览器授权时先看这个:访问密钥签发了却写不进去的话,会留下一个没人拿着的
225
- const { url, key, saved } = await resolveTarget({ id: 'codex', name: 'Codex' }, options, {
226
- ...io,
227
- beforeLogin: refuseUnsupported,
228
- })
229
- // 地址与访问密钥都定下来之后、写文件之前再看一次
230
- refuseUnsupported()
231
-
232
- const before = blockValues(found)
233
- const sameBlock = Boolean(before && key && before.url === url && before.key === key)
234
- const changes = []
235
- if (!sameBlock) {
236
- const was = !before ? '(未设置)' : before.rawUrl ? shown(before.rawUrl) : '(认不出的写法)'
237
- // 地址没变时只是换访问密钥,不把同一个地址写两遍
238
- if (before?.url === url) changes.push(` ${SERVER}:换访问密钥`)
239
- else changes.push(` ${SERVER}:${was} → ${shown(url)}/v1/mcp`)
240
- }
241
- if (found.memories?.value) changes.push(' features.memories:true → false')
242
- const profile = profileFile('codex', env)
243
- const sameProfile = Boolean(saved && saved.url === url && saved.key === key)
244
-
245
- if (!changes.length) out.write(`${file} 不用改\n`)
246
- else out.write(`${file}\n${changes.join('\n')}\n`)
247
- if (!sameProfile) out.write(`${profile}:写入服务地址与访问密钥(只给本人读写)\n`)
248
- if (options.dryRun) {
249
- out.write('没有写入(--dry-run)\n')
250
- return 0
251
- }
252
- if (changes.length) {
253
- const body = sameBlock
254
- ? rewrite(found, null, { memoriesOff: true, keep: true })
255
- : rewrite(found, blockOf({ url, key }), { memoriesOff: true })
256
- const backedUp = await safeWrite(file, body, text, { backup: !holdsKey(found) })
257
- if (backedUp) out.write(`原来的设置备份在 ${file}.kioku-backup\n`)
258
- }
259
- if (!sameProfile) await writeProfile('codex', { url, key }, env)
260
- if (found.memoriesUnknown) {
261
- out.write(
262
- `! ${file} 里 features 的写法认不出来,没有核对 Memories:运行 codex features disable memories 关掉它\n`,
263
- )
264
- }
265
- out.write(`Codex 已配好,新开会话生效。\n${found.plugin || io.hints === false ? '' : NEXT_STEPS}`)
266
- return 0
267
- }
268
-
269
- // kioku login 申请之前先看:config.toml 写不写得进去
270
- export async function preflightCodex({ env }) {
271
- const file = join(codexHome(env), 'config.toml')
272
- if (scanConfig(await readText(file)).unsupported) {
273
- throw new KiokuFailure(
274
- `${file} 里已经用行内表或带点的键定义了 kioku 这个 MCP 服务:删掉那个定义后重新运行`,
275
- )
276
- }
277
- }
278
-
279
- export async function inspectCodex({ env }, { ok, warn, bad, note }) {
280
- const file = join(codexHome(env), 'config.toml')
281
- const found = scanConfig(await readText(file))
282
- const profile = await readProfile('codex', env).catch(() => null)
283
- if (!profile) {
284
- warn('没有 kioku setup codex 写下的地址与访问密钥,钩子不会生效:运行 kioku setup codex')
285
- }
286
-
287
- const block = blockValues(found)
288
- if (found.unsupported) {
289
- warn(`${file} 里的 kioku 服务用了行内表或带点的键,没有核对它:改成 kioku setup codex 的写法`)
290
- } else if (!block) {
291
- warn(`${file} 里没有 Kioku 的 MCP 服务,读写记忆的工具用不了:运行 kioku setup codex`)
292
- } else if (profile && (block.url !== profile.url || block.key !== profile.key)) {
293
- bad(`${file} 里 Kioku 的 MCP 服务和钩子用的地址或访问密钥对不上:重新运行 kioku setup codex`)
294
- } else ok('Codex 里配了 Kioku 的 MCP 服务')
295
-
296
- if (found.plugin) ok('Codex 的 kioku 插件已启用')
297
- else {
298
- warn(
299
- `Codex 的 kioku 插件没有启用:codex plugin marketplace add ${MARKETPLACE},再 codex plugin add kioku@kioku`,
300
- )
301
- }
302
- note('钩子要在 Codex 的 /hooks 里信任过才会运行,这里查不到')
303
-
304
- if (found.memoriesUnknown && !found.memories) {
305
- warn(`${file} 里 features 的写法认不出来,没有核对 Memories:用 codex features list 看它开没开`)
306
- } else if (found.memories?.value) {
307
- warn('Codex 自带的 Memories 开着,会和 Kioku 各记一份:运行 kioku setup codex 关掉它')
308
- } else ok('Codex 自带的 Memories 没有启用')
309
- }
310
-
311
- // 给向导的面板:插件启用没有、自带的 Memories 关了没有(null 是认不出)
312
- export async function statusCodex({ env }) {
313
- const found = scanConfig(await readText(join(codexHome(env), 'config.toml')))
314
- const memory = found.memories?.value
315
- ? 'on'
316
- : found.memoriesUnknown && !found.memories
317
- ? null
318
- : 'off'
319
- return { plugin: found.plugin, memory }
320
- }
package/lib/connect.mjs DELETED
@@ -1,152 +0,0 @@
1
- // 把几个平台接到 Kioku:拿到访问密钥之后交给各平台的 kioku setup 写下(核对、写文件都照它的规矩)。
2
- // 向导走浏览器授权,几个平台一起申请、只确认一次;服务端不认这种写法时逐个平台申请。
3
- // kioku install 的访问密钥从环境变量来,直接写下。插件不替用户装,只列出要运行的命令
4
-
5
- import { KiokuFailure } from './http.mjs'
6
- import { deviceLogin, deviceLoginMany, LegacyServer, MAX_PLATFORMS } from './login.mjs'
7
- import { PLATFORMS } from './platforms.mjs'
8
- import { plain } from './text.mjs'
9
-
10
- // 访问密钥已经签发、却没有写下来:说清楚,别让它悄悄留着。kioku login 也用它
11
- export function orphanHint(app) {
12
- const name = app?.name ? `(应用 ${plain(app.name)})` : ''
13
- return `访问密钥已经签发、但没有写下:到管理界面的应用页吊销它${name},解决上面的问题后重新运行`
14
- }
15
-
16
- // 用给定的地址与访问密钥配好一个平台。setup 的输出写到 out;hints 为假时不打印「接下来装上」,
17
- // 由调用方统一列出(向导与 kioku install),kioku login 只配一个平台,照旧打印
18
- export function configure(id, { url, key }, { env, out, cwd }, { hints = false } = {}) {
19
- return PLATFORMS[id].setup(
20
- { serverUrl: url, dryRun: false, undo: false, check: true },
21
- { env, out, cwd, readKey: async () => key, plain, login: null, hints },
22
- )
23
- }
24
-
25
- // 签发好的访问密钥写下;写不下时提醒去吊销
26
- async function settle(id, key, app, io) {
27
- io.out.write(`\n${PLATFORMS[id].name}\n`)
28
- try {
29
- await configure(id, { url: io.url, key }, io)
30
- return { id, status: 'connected', app }
31
- } catch (err) {
32
- // 别的错误照旧抛出(由入口报内部错误),不当成一个平台的失败吞掉
33
- if (!(err instanceof KiokuFailure)) throw err
34
- return { id, status: 'failed', reason: `${err.message}。${orphanHint(app)}` }
35
- }
36
- }
37
-
38
- // 用浏览器授权把这几个平台接到 url。返回每个平台的结果(按 ids 的顺序):
39
- // { id, status: 'connected' | 'skipped' | 'denied' | 'failed', reason?, app? }
40
- export async function connectPlatforms(
41
- { url, ids },
42
- { env, out, cwd, open, browser = true, clientName, sleep, now },
43
- ) {
44
- const io = { env, out, cwd, url }
45
- const login = { out, open, browser, sleep, now, ...(clientName ? { clientName } : {}) }
46
- const results = new Map()
47
- // 申请之前先看各平台的配置写不写得进去:访问密钥只在签发时给一次
48
- const ready = []
49
- for (const id of ids) {
50
- try {
51
- await PLATFORMS[id].preflight?.({ env, cwd })
52
- ready.push(id)
53
- } catch (err) {
54
- if (!(err instanceof KiokuFailure)) throw err
55
- results.set(id, { id, status: 'failed', reason: err.message })
56
- }
57
- }
58
- // 一次最多 MAX_PLATFORMS 个:多了分批,每批确认一次,前一批签发的先写下再申请下一批
59
- const batches = []
60
- for (let i = 0; i < ready.length; i += MAX_PLATFORMS) {
61
- batches.push(ready.slice(i, i + MAX_PLATFORMS))
62
- }
63
- if (batches.length > 1) {
64
- out.write(`一次最多申请 ${MAX_PLATFORMS} 个平台:分 ${batches.length} 批,每批确认一次\n`)
65
- }
66
- let legacy = false
67
- for (const batch of batches) {
68
- out.write(
69
- `这次申请 ${batch.length} 个平台:${batch.map((id) => PLATFORMS[id].name).join('、')}\n`,
70
- )
71
- let answers
72
- try {
73
- answers = await deviceLoginMany(
74
- { url, runtimeFamilies: batch.map((id) => PLATFORMS[id].runtimeFamily) },
75
- login,
76
- )
77
- } catch (err) {
78
- if (err instanceof LegacyServer) {
79
- legacy = true
80
- out.write(`${err.message}\n`)
81
- break
82
- }
83
- if (!(err instanceof KiokuFailure)) throw err
84
- for (const id of batch) results.set(id, { id, status: 'failed', reason: err.message })
85
- continue
86
- }
87
- for (const id of batch) {
88
- const answer = answers.find((item) => item.runtimeFamily === PLATFORMS[id].runtimeFamily)
89
- if (answer?.status === 'issued') results.set(id, await settle(id, answer.key, answer.app, io))
90
- else if (answer?.status === 'denied') {
91
- results.set(id, { id, status: 'denied', reason: answer.reason || '没有签发' })
92
- } else results.set(id, { id, status: 'skipped', reason: '确认页上没有勾选' })
93
- }
94
- }
95
- if (legacy) {
96
- // 旧的服务端:还没有结果的平台逐个申请,每个确认一次;一个不成不影响下一个
97
- for (const id of ready.filter((item) => !results.has(item))) {
98
- out.write(`\n${PLATFORMS[id].name}:浏览器授权\n`)
99
- let key
100
- try {
101
- key = await deviceLogin({ url, runtimeFamily: PLATFORMS[id].runtimeFamily }, login)
102
- } catch (err) {
103
- if (!(err instanceof KiokuFailure)) throw err
104
- results.set(id, { id, status: 'failed', reason: err.message })
105
- continue
106
- }
107
- results.set(id, await settle(id, key, null, io))
108
- }
109
- }
110
- return ids.map((id) => results.get(id))
111
- }
112
-
113
- const STATUS_NAMES = {
114
- connected: '已接入',
115
- manual: '待完成',
116
- skipped: '跳过',
117
- denied: '被拒绝',
118
- failed: '失败',
119
- }
120
-
121
- // 结果的文字:按状态分组,一组一行,原因跟在平台名后面
122
- export function resultsText(results) {
123
- const lines = []
124
- for (const status of Object.keys(STATUS_NAMES)) {
125
- const group = results.filter((item) => item.status === status)
126
- if (!group.length) continue
127
- const names = group.map((item) => {
128
- const detail = item.reason ?? (item.app?.name ? `应用 ${plain(item.app.name)}` : '')
129
- return detail ? `${PLATFORMS[item.id].name}(${detail})` : PLATFORMS[item.id].name
130
- })
131
- lines.push(`${STATUS_NAMES[status]}:${names.join('、')}`)
132
- }
133
- return lines.join('\n')
134
- }
135
-
136
- // 这几个平台里还要自己装插件的(查得到装好了的不列),每个平台一段:在哪里运行、可以直接复制的命令、之后要做的事。
137
- // 访问密钥在插件配置里填的平台(Claude Code),给了 url 时写明要填的服务地址
138
- export async function pluginSteps(ids, { env, cwd, url }) {
139
- const blocks = []
140
- for (const id of ids) {
141
- const platform = PLATFORMS[id]
142
- const status = await platform.status({ env, cwd }).catch(() => ({ plugin: null }))
143
- if (status.plugin === true) continue
144
- const { where = '在终端里', commands, after } = platform.install
145
- const lines = [`${platform.name}(${where}运行)`, ...commands.map((line) => ` ${line}`)]
146
- if (!platform.setup && url) lines.push(` 服务地址填:${url}`)
147
- lines.push(` 然后:${after}`)
148
- blocks.push(lines.join('\n'))
149
- }
150
- if (!blocks.length) return ''
151
- return `接下来自己装插件,装好之后再运行 kioku 看状态:\n\n${blocks.join('\n\n')}`
152
- }