@kioku-memory/plugin-opencode 0.1.0 → 0.4.1
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 +35 -433
- package/lib/run.mjs +372 -0
- package/package.json +15 -1
- package/lib/agy.mjs +0 -181
- package/lib/api.mjs +0 -38
- package/lib/clean.mjs +0 -96
- package/lib/codex.mjs +0 -320
- package/lib/conflicts.mjs +0 -1303
- package/lib/connect.mjs +0 -152
- package/lib/doctor.mjs +0 -158
- package/lib/dsh.mjs +0 -82
- package/lib/files.mjs +0 -92
- package/lib/gemini.mjs +0 -199
- package/lib/hermes.mjs +0 -276
- package/lib/import.mjs +0 -301
- package/lib/install.mjs +0 -196
- package/lib/local.mjs +0 -294
- package/lib/login.mjs +0 -359
- package/lib/openclaw.mjs +0 -256
- package/lib/opencode.mjs +0 -144
- package/lib/panel.mjs +0 -311
- package/lib/pi.mjs +0 -90
- package/lib/platforms.mjs +0 -297
- package/lib/prompts.mjs +0 -38
- package/lib/secret.mjs +0 -86
- package/lib/setup.mjs +0 -139
- package/lib/sources.mjs +0 -333
- package/lib/target.mjs +0 -62
- package/lib/wizard.mjs +0 -534
package/lib/install.mjs
DELETED
|
@@ -1,196 +0,0 @@
|
|
|
1
|
-
// kioku install:给脚本用的接入。几个平台一起配好,访问密钥按平台从环境变量取(KIOKU_API_KEY_CODEX 这类),
|
|
2
|
-
// 没给的平台跳过并列出来。插件不替用户装,最后列出要运行的命令
|
|
3
|
-
|
|
4
|
-
import { whoami } from './api.mjs'
|
|
5
|
-
import { conflictToolsText, formatConflicts, removeConflicts, scanConflicts } from './conflicts.mjs'
|
|
6
|
-
import { configure, pluginSteps, resultsText } from './connect.mjs'
|
|
7
|
-
import { failureText, keyFormatError, KiokuFailure } from './http.mjs'
|
|
8
|
-
import { confirm } from './import.mjs'
|
|
9
|
-
import { platformNames, PLATFORMS } from './platforms.mjs'
|
|
10
|
-
import { setup } from './setup.mjs'
|
|
11
|
-
import { resolveServerUrl } from './target.mjs'
|
|
12
|
-
import { plain, shownUrl } from './text.mjs'
|
|
13
|
-
import { UsageError } from './usage.mjs'
|
|
14
|
-
|
|
15
|
-
// 平台的访问密钥放在哪个环境变量里:平台 id 大写、连字符换成下划线
|
|
16
|
-
export function keyVariable(id) {
|
|
17
|
-
return `KIOKU_API_KEY_${id.toUpperCase().replaceAll('-', '_')}`
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
export const INSTALL_USAGE = `用法:kioku install --platforms <平台,…> [--server-url <地址>] [-y] [--dry-run]
|
|
21
|
-
|
|
22
|
-
把几个平台一起接到 Kioku(给脚本用;在终端里直接运行 kioku 是交互式的向导)。
|
|
23
|
-
每个平台的访问密钥从它的环境变量读,没给的平台跳过:
|
|
24
|
-
|
|
25
|
-
${Object.keys(PLATFORMS)
|
|
26
|
-
.map((id) => ` ${keyVariable(id).padEnd(28)}${PLATFORMS[id].name}`)
|
|
27
|
-
.join('\n')}
|
|
28
|
-
|
|
29
|
-
--platforms <平台,…> 逗号分隔:${platformNames().replaceAll('、', ',')}
|
|
30
|
-
--server-url <地址> Kioku 的服务地址(也可以用 KIOKU_SERVER_URL)
|
|
31
|
-
-y, --yes 不问,直接写(在终端里运行时默认先列计划再确认)
|
|
32
|
-
--dry-run 只列计划,不写
|
|
33
|
-
--remove-conflicts 接入前先卸载各平台上已有的冲突记忆工具(Lore 及常见记忆 MCP)
|
|
34
|
-
|
|
35
|
-
各平台照 kioku setup 写下地址与访问密钥、停用自带的长期记忆。
|
|
36
|
-
Claude Code 的访问密钥在它的 /plugin 里填:这里只核对访问密钥、停用自动记忆。
|
|
37
|
-
插件不替你装:最后列出要运行的命令,装好之后运行 kioku doctor <平台> 检查。
|
|
38
|
-
`
|
|
39
|
-
|
|
40
|
-
export function parseInstallArgs(argv) {
|
|
41
|
-
const options = {
|
|
42
|
-
platforms: [],
|
|
43
|
-
serverUrl: undefined,
|
|
44
|
-
yes: false,
|
|
45
|
-
dryRun: false,
|
|
46
|
-
removeConflicts: false,
|
|
47
|
-
}
|
|
48
|
-
let given = false
|
|
49
|
-
for (let i = 0; i < argv.length; i++) {
|
|
50
|
-
const arg = argv[i]
|
|
51
|
-
if (arg === '-y' || arg === '--yes') options.yes = true
|
|
52
|
-
else if (arg === '--dry-run') options.dryRun = true
|
|
53
|
-
else if (arg === '--remove-conflicts') options.removeConflicts = true
|
|
54
|
-
else if (arg === '--server-url' || arg === '--platforms') {
|
|
55
|
-
const value = argv[++i]
|
|
56
|
-
if (!value) throw new UsageError(`${arg} 后面要写值`)
|
|
57
|
-
if (arg === '--server-url') options.serverUrl = value
|
|
58
|
-
else {
|
|
59
|
-
given = true
|
|
60
|
-
for (const name of value.split(',').map((item) => item.trim())) {
|
|
61
|
-
if (!name) continue
|
|
62
|
-
if (!Object.hasOwn(PLATFORMS, name)) {
|
|
63
|
-
throw new UsageError(`不认识的平台 ${name},可以用的:${platformNames()}`)
|
|
64
|
-
}
|
|
65
|
-
if (!options.platforms.includes(name)) options.platforms.push(name)
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
} else throw new UsageError(`不认识的参数 ${arg}`)
|
|
69
|
-
}
|
|
70
|
-
if (!given || !options.platforms.length) throw new UsageError('要写平台:--platforms codex,pi')
|
|
71
|
-
return options
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
// 每个平台要做什么:{ id, key } 或 { id, skip: 原因 }
|
|
75
|
-
export function installPlan(platforms, env) {
|
|
76
|
-
return platforms.map((id) => {
|
|
77
|
-
const name = keyVariable(id)
|
|
78
|
-
const key = (env[name] ?? '').trim()
|
|
79
|
-
if (!key) return { id, skip: `没有 ${name}` }
|
|
80
|
-
const problem = keyFormatError(key)
|
|
81
|
-
if (problem) return { id, skip: `${name}:${problem}` }
|
|
82
|
-
return { id, key }
|
|
83
|
-
})
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
// Claude Code:核对访问密钥是不是给它的,停用自动记忆;地址与访问密钥要用户在 /plugin 里填
|
|
87
|
-
async function installClaudeCode(url, key, { env, out, cwd }) {
|
|
88
|
-
const who = await whoami({ url, key })
|
|
89
|
-
out.write(`✓ 访问密钥可用:应用 ${plain(who.app.name)},运行时 ${plain(who.app.runtimeFamily)}\n`)
|
|
90
|
-
if (who.app.runtimeFamily !== PLATFORMS['claude-code'].runtimeFamily) {
|
|
91
|
-
out.write('! 这个应用的运行时不是 claudecode:在管理界面为 Claude Code 另建一个应用\n')
|
|
92
|
-
}
|
|
93
|
-
const code = await setup(['claude-code'], { env, out, cwd, login: null, skipConflicts: true })
|
|
94
|
-
if (code !== 0) throw new KiokuFailure('停用自动记忆没有成功')
|
|
95
|
-
out.write('地址与访问密钥要在 Claude Code 的 /plugin 里填(启用插件时会问)\n')
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
export async function install(
|
|
99
|
-
argv,
|
|
100
|
-
{ env = process.env, out = process.stdout, cwd = process.cwd(), stdin = process.stdin } = {},
|
|
101
|
-
) {
|
|
102
|
-
const options = parseInstallArgs(argv)
|
|
103
|
-
const url = resolveServerUrl(options, env, null)
|
|
104
|
-
const plan = installPlan(options.platforms, env)
|
|
105
|
-
const todo = plan.filter((item) => item.key)
|
|
106
|
-
const conflictsByPlatform = new Map()
|
|
107
|
-
for (const { id } of todo) {
|
|
108
|
-
const found = await scanConflicts(id, { env, cwd })
|
|
109
|
-
conflictsByPlatform.set(id, {
|
|
110
|
-
removable: found.filter((c) => c.removable),
|
|
111
|
-
warnings: found.filter((c) => !c.removable),
|
|
112
|
-
})
|
|
113
|
-
}
|
|
114
|
-
const canPromptRemove = !options.yes && stdin.isTTY
|
|
115
|
-
const willRemove = options.removeConflicts || canPromptRemove
|
|
116
|
-
|
|
117
|
-
out.write(`Kioku:${shownUrl(url)}\n`)
|
|
118
|
-
for (const item of plan) {
|
|
119
|
-
const name = PLATFORMS[item.id].name
|
|
120
|
-
if (item.skip) out.write(` 跳过 ${name}(${item.skip})\n`)
|
|
121
|
-
else if (item.id === 'claude-code') out.write(` 核对 ${name}:核对访问密钥,停用自动记忆\n`)
|
|
122
|
-
else out.write(` 接入 ${name}:写下地址与访问密钥,停用自带的长期记忆\n`)
|
|
123
|
-
const entry = conflictsByPlatform.get(item.id)
|
|
124
|
-
if (entry?.removable.length) {
|
|
125
|
-
const action = willRemove
|
|
126
|
-
? '先卸载再接入'
|
|
127
|
-
: `需先清理:运行 kioku clean ${item.id} 或加 --remove-conflicts`
|
|
128
|
-
out.write(` 冲突 ${name}:发现 ${conflictToolsText(entry.removable)}(${action})\n`)
|
|
129
|
-
out.write(`${formatConflicts(entry.removable, PLATFORMS).join('\n')}\n`)
|
|
130
|
-
}
|
|
131
|
-
for (const w of entry?.warnings ?? []) {
|
|
132
|
-
out.write(` 提示 ${name}:${w.toolName} ${w.summary}\n`)
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
if (options.dryRun) {
|
|
136
|
-
out.write('没有写入(--dry-run)\n')
|
|
137
|
-
return 0
|
|
138
|
-
}
|
|
139
|
-
if (!todo.length) {
|
|
140
|
-
out.write('没有要接入的平台:按上面的变量名给出访问密钥\n')
|
|
141
|
-
return 1
|
|
142
|
-
}
|
|
143
|
-
let removeApproved = options.removeConflicts
|
|
144
|
-
if (canPromptRemove) {
|
|
145
|
-
const hasConflicts = todo.some(({ id }) => conflictsByPlatform.get(id)?.removable.length)
|
|
146
|
-
const prompt = hasConflicts
|
|
147
|
-
? `先卸载发现的冲突并接入这 ${todo.length} 个平台?[y/N] `
|
|
148
|
-
: `接入这 ${todo.length} 个平台?[y/N] `
|
|
149
|
-
if (!(await confirm(prompt, { stdin, out }))) {
|
|
150
|
-
out.write('没有写入\n')
|
|
151
|
-
return 0
|
|
152
|
-
}
|
|
153
|
-
if (hasConflicts) removeApproved = true
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
const results = plan
|
|
157
|
-
.filter((item) => item.skip)
|
|
158
|
-
.map((item) => ({ ...item, status: 'skipped', reason: item.skip }))
|
|
159
|
-
for (const { id, key } of todo) {
|
|
160
|
-
out.write(`\n${PLATFORMS[id].name}\n`)
|
|
161
|
-
const entry = conflictsByPlatform.get(id)
|
|
162
|
-
if (entry?.removable.length) {
|
|
163
|
-
if (!removeApproved) {
|
|
164
|
-
const reason = `存在冲突(${conflictToolsText(entry.removable)}):运行 kioku clean ${id},或加 --remove-conflicts`
|
|
165
|
-
results.push({ id, status: 'failed', reason })
|
|
166
|
-
continue
|
|
167
|
-
}
|
|
168
|
-
const cleanResults = await removeConflicts(entry.removable, { env, cwd, out })
|
|
169
|
-
if (cleanResults.some((r) => !r.ok)) {
|
|
170
|
-
results.push({ id, status: 'failed', reason: '清理冲突没有全部成功' })
|
|
171
|
-
continue
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
try {
|
|
175
|
-
if (id === 'claude-code') {
|
|
176
|
-
await installClaudeCode(url, key, { env, out, cwd })
|
|
177
|
-
results.push({ id, status: 'manual', reason: '地址与访问密钥在 /plugin 里填' })
|
|
178
|
-
} else {
|
|
179
|
-
await configure(id, { url, key }, { env, out, cwd })
|
|
180
|
-
results.push({ id, status: 'connected' })
|
|
181
|
-
}
|
|
182
|
-
} catch (err) {
|
|
183
|
-
results.push({ id, status: 'failed', reason: failureText(err) })
|
|
184
|
-
}
|
|
185
|
-
}
|
|
186
|
-
const ordered = options.platforms.map((id) => results.find((item) => item.id === id))
|
|
187
|
-
out.write(`\n${resultsText(ordered)}\n`)
|
|
188
|
-
const steps = await pluginSteps(
|
|
189
|
-
ordered
|
|
190
|
-
.filter((item) => item.status === 'connected' || item.status === 'manual')
|
|
191
|
-
.map((item) => item.id),
|
|
192
|
-
{ env, cwd, url },
|
|
193
|
-
)
|
|
194
|
-
if (steps) out.write(`\n${steps}\n`)
|
|
195
|
-
return ordered.some((item) => item.status === 'failed') ? 1 : 0
|
|
196
|
-
}
|
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
|
-
}
|