@cveo/dsh-containers 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +36 -2
- package/cordis.patch.yml +19 -0
- package/dist/client.js +5397 -0
- package/dist/host/core.js +1080 -0
- package/dist/host/extras-tools.js +63 -0
- package/dist/host/extras.js +410 -0
- package/dist/host/index.js +225 -0
- package/dist/host/tools.js +283 -0
- package/icon.svg +5 -0
- package/locale/core/en.json +6 -0
- package/locale/core/zh.json +6 -0
- package/locale/en.json +241 -0
- package/locale/extras/en.json +6 -0
- package/locale/extras/zh.json +6 -0
- package/locale/extras-tools/en.json +6 -0
- package/locale/extras-tools/zh.json +6 -0
- package/locale/tools/en.json +6 -0
- package/locale/tools/zh.json +6 -0
- package/locale/zh.json +241 -0
- package/package.json +73 -3
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// packages/dsh-containers-extras/src/host/extras-tools.js
|
|
2
|
+
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
3
|
+
var TEXT_OUTPUT = {
|
|
4
|
+
schema: { type: "string" },
|
|
5
|
+
render: (_args, value) => [{ type: "text", text: value }]
|
|
6
|
+
};
|
|
7
|
+
function clip(text, max = 4e3) {
|
|
8
|
+
return text.length <= max ? text : `${text.slice(0, max)}
|
|
9
|
+
…(已截断,共 ${text.length} 字符)`;
|
|
10
|
+
}
|
|
11
|
+
var inject = ["tools", "containersExtras"];
|
|
12
|
+
function apply(ctx, config = {}) {
|
|
13
|
+
const extras = ctx.containersExtras;
|
|
14
|
+
ctx.tools.register(defineTool({
|
|
15
|
+
name: "containers_k8s",
|
|
16
|
+
description: "启动 kiri 单节点 Kubernetes(k3s,约 20 秒就绪,注册为 kiri kubectl 上下文)。需要本机安装 kiri CLI。",
|
|
17
|
+
parameters: {},
|
|
18
|
+
output: TEXT_OUTPUT,
|
|
19
|
+
async execute() {
|
|
20
|
+
const result = await extras.k8sStart();
|
|
21
|
+
if (result.missing) return "本机未安装 kiri CLI,无法启动 Kubernetes。";
|
|
22
|
+
if (!result.ok) return `kiri k8s start 失败:${result.error || result.output || "未知错误"}`;
|
|
23
|
+
return `Kubernetes 已启动${result.output ? `:${result.output}` : "(kiri kubectl 上下文)"}`;
|
|
24
|
+
}
|
|
25
|
+
}));
|
|
26
|
+
ctx.tools.register(defineTool({
|
|
27
|
+
name: "containers_machine",
|
|
28
|
+
description: "创建一台 kiri Linux 虚拟机(kiri machine create)。需要本机安装 kiri CLI。",
|
|
29
|
+
parameters: {
|
|
30
|
+
name: { type: "string", required: true, description: "虚拟机名称" },
|
|
31
|
+
distro: { type: "string", description: "发行版,默认 ubuntu" }
|
|
32
|
+
},
|
|
33
|
+
output: TEXT_OUTPUT,
|
|
34
|
+
async execute(args) {
|
|
35
|
+
const name = String(args.name || "").trim();
|
|
36
|
+
if (!name) throw new Error("缺少虚拟机名称");
|
|
37
|
+
const result = await extras.machineCreate(name, args.distro);
|
|
38
|
+
if (result.missing) return "本机未安装 kiri CLI,无法创建虚拟机。";
|
|
39
|
+
if (!result.ok) return `创建虚拟机失败:${result.error || result.output || "未知错误"}`;
|
|
40
|
+
return `虚拟机已创建${result.output ? `:${result.output}` : `:${name}(可用 kiri machine shell ${name} 进入)`}`;
|
|
41
|
+
}
|
|
42
|
+
}));
|
|
43
|
+
ctx.tools.register(defineTool({
|
|
44
|
+
name: "containers_compose",
|
|
45
|
+
description: "用 kiri 运行 Compose 项目(kiri compose,等价 docker compose):up / down / ps / logs。需要本机安装 kiri CLI。",
|
|
46
|
+
parameters: {
|
|
47
|
+
action: { type: "string", required: true, description: "up | down | ps | logs" },
|
|
48
|
+
file: { type: "string", required: true, description: "compose 文件的绝对路径(如 D:\\app\\docker-compose.yml)" }
|
|
49
|
+
},
|
|
50
|
+
output: TEXT_OUTPUT,
|
|
51
|
+
async execute(args) {
|
|
52
|
+
const result = await extras.compose(args.action, args.file);
|
|
53
|
+
if (result.missing) return "本机未安装 kiri CLI,无法执行 compose。";
|
|
54
|
+
if (!result.ok) return `compose ${args.action} 失败:${result.error || result.output || "未知错误"}`;
|
|
55
|
+
return `compose ${args.action} 完成${result.output ? `:
|
|
56
|
+
${clip(result.output)}` : ""}`;
|
|
57
|
+
}
|
|
58
|
+
}));
|
|
59
|
+
}
|
|
60
|
+
export {
|
|
61
|
+
apply,
|
|
62
|
+
inject
|
|
63
|
+
};
|
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
// packages/dsh-containers-extras/src/host/extras.js
|
|
2
|
+
import { Service } from "@deepseek-ai/cordis";
|
|
3
|
+
import z from "@deepseek-ai/schemastery";
|
|
4
|
+
|
|
5
|
+
// packages/dsh-containers-core/src/host/server-utils.js
|
|
6
|
+
function sendJson(response, status, payload, request) {
|
|
7
|
+
const body = JSON.stringify(payload);
|
|
8
|
+
response.writeHead(status, {
|
|
9
|
+
"content-type": "application/json; charset=utf-8",
|
|
10
|
+
"cache-control": "no-store",
|
|
11
|
+
"content-length": Buffer.byteLength(body)
|
|
12
|
+
});
|
|
13
|
+
response.end(request?.method === "HEAD" ? void 0 : body);
|
|
14
|
+
}
|
|
15
|
+
async function readJsonBody(request) {
|
|
16
|
+
const chunks = [];
|
|
17
|
+
let size = 0;
|
|
18
|
+
for await (const chunk of request) {
|
|
19
|
+
size += chunk.length;
|
|
20
|
+
if (size > 65536) throw new Error("请求体过大");
|
|
21
|
+
chunks.push(chunk);
|
|
22
|
+
}
|
|
23
|
+
if (chunks.length === 0) return null;
|
|
24
|
+
const text = Buffer.concat(chunks).toString("utf8").trim();
|
|
25
|
+
if (!text) return null;
|
|
26
|
+
return JSON.parse(text);
|
|
27
|
+
}
|
|
28
|
+
function route(allowed, handler) {
|
|
29
|
+
return async (request, response) => {
|
|
30
|
+
if (allowed.length > 0 && !allowed.includes(request.method)) {
|
|
31
|
+
sendJson(response, 405, { ok: false, error: "method not allowed" }, request);
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
try {
|
|
35
|
+
await handler(request, response);
|
|
36
|
+
} catch (error) {
|
|
37
|
+
sendJson(response, 500, { ok: false, error: String(error?.message ?? error) }, request);
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// packages/dsh-containers-core/src/host/kiri-cli.js
|
|
43
|
+
import { execFile } from "node:child_process";
|
|
44
|
+
import fs from "node:fs";
|
|
45
|
+
import os from "node:os";
|
|
46
|
+
import path from "node:path";
|
|
47
|
+
var PROBE_TTL_MS = 6e4;
|
|
48
|
+
var KiriCli = class {
|
|
49
|
+
/** @param {object} config 归一化配置(cliPath 等)。 */
|
|
50
|
+
constructor(config = {}) {
|
|
51
|
+
this.cliPath = config.cliPath || "kiri";
|
|
52
|
+
this.probeCache = null;
|
|
53
|
+
this.vmCache = null;
|
|
54
|
+
}
|
|
55
|
+
/** 执行一条 kiri 子命令;返回 { ok, code, output, error, missing },不抛错。 */
|
|
56
|
+
run(args, { timeoutMs = 3e4 } = {}) {
|
|
57
|
+
return new Promise((resolve) => {
|
|
58
|
+
execFile(
|
|
59
|
+
this.cliPath,
|
|
60
|
+
args,
|
|
61
|
+
{ timeout: timeoutMs, windowsHide: true, maxBuffer: 4 * 1024 * 1024 },
|
|
62
|
+
(error, stdout, stderr) => {
|
|
63
|
+
const out = String(stdout || "");
|
|
64
|
+
const err = String(stderr || "");
|
|
65
|
+
if (error && error.code === "ENOENT") {
|
|
66
|
+
resolve({ ok: false, missing: true, code: null, output: "", error: `未找到 kiri CLI(${this.cliPath})` });
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
if (error && !out && !err) {
|
|
70
|
+
resolve({ ok: false, missing: false, code: error.code ?? null, output: "", error: String(error.message) });
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
resolve({ ok: error == null, missing: false, code: error?.code ?? 0, output: `${out}${err}`.trim(), error: null });
|
|
74
|
+
}
|
|
75
|
+
);
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
/** kiri CLI 可用性与版本;结果缓存 60 秒。 */
|
|
79
|
+
async probe({ force = false } = {}) {
|
|
80
|
+
if (this.probeCache && !force && Date.now() - this.probeCache.at < PROBE_TTL_MS) {
|
|
81
|
+
return this.probeCache.result;
|
|
82
|
+
}
|
|
83
|
+
let result = await this.run(["--version"], { timeoutMs: 5e3 });
|
|
84
|
+
if (!result.missing && !result.ok) {
|
|
85
|
+
result = await this.run(["version"], { timeoutMs: 5e3 });
|
|
86
|
+
}
|
|
87
|
+
const normalized = result.missing ? { ok: false, missing: true, version: "", error: result.error } : result.ok ? { ok: true, missing: false, version: result.output.split(/\r?\n/)[0]?.trim() || "", error: null } : { ok: false, missing: false, version: "", error: result.output || result.error };
|
|
88
|
+
this.probeCache = { at: Date.now(), result: normalized };
|
|
89
|
+
return normalized;
|
|
90
|
+
}
|
|
91
|
+
/** ~/.kiri/vm.json(KIRI_DATA_DIR 可覆盖)里的虚拟机资源;读不到就返回 null。 */
|
|
92
|
+
vmConfig() {
|
|
93
|
+
if (this.vmCache && Date.now() - this.vmCache.at < PROBE_TTL_MS) return this.vmCache.value;
|
|
94
|
+
let value = null;
|
|
95
|
+
try {
|
|
96
|
+
const file = path.join(process.env.KIRI_DATA_DIR || path.join(os.homedir(), ".kiri"), "vm.json");
|
|
97
|
+
const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
98
|
+
const pick = (raw) => Number.isFinite(Number(raw)) ? Number(raw) : void 0;
|
|
99
|
+
const cpus = pick(parsed?.cpus);
|
|
100
|
+
const memoryMiB = pick(parsed?.memoryMiB ?? parsed?.memory_mib);
|
|
101
|
+
if (cpus !== void 0 || memoryMiB !== void 0) value = { cpus, memoryMiB };
|
|
102
|
+
} catch {
|
|
103
|
+
value = null;
|
|
104
|
+
}
|
|
105
|
+
this.vmCache = { at: Date.now(), value };
|
|
106
|
+
return value;
|
|
107
|
+
}
|
|
108
|
+
/** 启动 kiri 单节点 Kubernetes(k3s,约 20 秒就绪,kubectl 上下文 kiri)。 */
|
|
109
|
+
k8sStart() {
|
|
110
|
+
return this.run(["k8s", "start"], { timeoutMs: 18e4 });
|
|
111
|
+
}
|
|
112
|
+
/** 创建 kiri Linux 虚拟机(kiri machine create <name> --distro <distro>)。 */
|
|
113
|
+
machineCreate(name, distro = "ubuntu") {
|
|
114
|
+
return this.run(["machine", "create", String(name), "--distro", String(distro || "ubuntu")], { timeoutMs: 3e5 });
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
// packages/dsh-containers-extras/src/host/setup.js
|
|
119
|
+
import { execFile as execFile2 } from "node:child_process";
|
|
120
|
+
import fs2 from "node:fs/promises";
|
|
121
|
+
import os2 from "node:os";
|
|
122
|
+
import path2 from "node:path";
|
|
123
|
+
|
|
124
|
+
// packages/dsh-containers-core/shared/version.js
|
|
125
|
+
function semverOf(text) {
|
|
126
|
+
const match = /(\d+)\.(\d+)\.(\d+)/.exec(String(text || ""));
|
|
127
|
+
return match ? match.slice(1).map(Number) : null;
|
|
128
|
+
}
|
|
129
|
+
function compareVersions(a, b) {
|
|
130
|
+
const left = semverOf(a);
|
|
131
|
+
const right = semverOf(b);
|
|
132
|
+
if (!left || !right) return 0;
|
|
133
|
+
for (let i = 0; i < 3; i++) {
|
|
134
|
+
if (left[i] !== right[i]) return left[i] > right[i] ? 1 : -1;
|
|
135
|
+
}
|
|
136
|
+
return 0;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// packages/dsh-containers-extras/src/host/setup.js
|
|
140
|
+
function pickMsiAsset(assets = []) {
|
|
141
|
+
const arch = os2.arch() === "arm64" ? "arm64" : "x86_64";
|
|
142
|
+
const candidates = (Array.isArray(assets) ? assets : []).filter((asset) => /\.msi$/i.test(String(asset?.browser_download_url || "")));
|
|
143
|
+
return candidates.find((asset) => new RegExp(`-${arch}\\.msi$`, "i").test(asset.browser_download_url)) ?? candidates.find((asset) => new RegExp(arch, "i").test(asset.name || "")) ?? candidates[0] ?? null;
|
|
144
|
+
}
|
|
145
|
+
function downloadProgressText(received, total) {
|
|
146
|
+
const mb = (n) => (n / 1048576).toFixed(1);
|
|
147
|
+
return total > 0 ? `下载中 ${mb(received)} / ${mb(total)} MB` : `下载中 ${mb(received)} MB`;
|
|
148
|
+
}
|
|
149
|
+
var KiriSetup = class {
|
|
150
|
+
/** @param {object} deps { kiriCli, engine } —— 安装完成后要立即重探的两样东西。 */
|
|
151
|
+
constructor({ kiriCli, engine, config = {} } = {}) {
|
|
152
|
+
this.kiriCli = kiriCli;
|
|
153
|
+
this.engine = engine;
|
|
154
|
+
this.releaseApi = config.releaseApi || "https://api.github.com/repos/libracoder/kiri/releases/latest";
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* 一键安装 kiri(Windows:官方 MSI 静默安装;非 Windows 平台给出手动指引)。
|
|
158
|
+
* 返回 { ok, stage, message },失败也绝不抛错——每一步的原因都要能显示在面板上。
|
|
159
|
+
*
|
|
160
|
+
* 与本机已有 kiri 的冲突防护(用户可能早已单独安装):
|
|
161
|
+
* 1. CLI 可用 → 永不重装/覆盖;已是最新则提示跳过,较旧则引导 `kiri update`
|
|
162
|
+
* (官方自更新命令,SHA-256 + 签名校验),绝不用我们的 MSI 动用户的安装
|
|
163
|
+
* 2. CLI 缺失但 kiri 引擎管道在响应 → 说明 kiri 装在非 PATH 位置,
|
|
164
|
+
* 提示用 cliPath 配置指向它,同样不安装
|
|
165
|
+
* 3. 仅在「CLI 缺失且 kiri 管道不可达」时才真正下载安装
|
|
166
|
+
*/
|
|
167
|
+
async installKiri({ onProgress = () => {
|
|
168
|
+
} } = {}) {
|
|
169
|
+
if (process.platform !== "win32") {
|
|
170
|
+
return {
|
|
171
|
+
ok: false,
|
|
172
|
+
stage: "unsupported",
|
|
173
|
+
message: `请从 https://github.com/libracoder/kiri/releases 手动安装 kiri(当前平台 ${process.platform} 暂不支持自动安装)`
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
const local = await this.kiriCli.probe();
|
|
177
|
+
if (local.ok) {
|
|
178
|
+
let latest = "";
|
|
179
|
+
try {
|
|
180
|
+
const response = await fetch(this.releaseApi, { headers: { "user-agent": "dsh-containers-plugin" }, signal: AbortSignal.timeout(2e4) });
|
|
181
|
+
latest = String((await response.json())?.tag_name || "").replace(/^v/, "");
|
|
182
|
+
} catch {
|
|
183
|
+
}
|
|
184
|
+
const cmp = latest ? compareVersions(local.version, latest) : 0;
|
|
185
|
+
if (cmp >= 0) {
|
|
186
|
+
return { ok: true, stage: "skip", message: `本机已安装 kiri ${local.version || ""}(最新 ${latest || "未知"}),无需安装;如需更新请运行 kiri update` };
|
|
187
|
+
}
|
|
188
|
+
return { ok: true, stage: "skip", message: `本机已安装 kiri ${local.version},最新版本 ${latest};如需升级请运行 kiri update(插件不会覆盖你的安装)` };
|
|
189
|
+
}
|
|
190
|
+
try {
|
|
191
|
+
await this.engine.detect({ force: true });
|
|
192
|
+
if (this.engine.detected?.label === "kiri") {
|
|
193
|
+
return {
|
|
194
|
+
ok: true,
|
|
195
|
+
stage: "skip",
|
|
196
|
+
message: "检测到 kiri 引擎正在运行,但 CLI 不在 PATH:请在插件配置里把 cliPath 指向 kiri 可执行文件(插件不会重复安装)"
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
} catch {
|
|
200
|
+
}
|
|
201
|
+
onProgress({ stage: "resolve", message: "获取最新版本信息…" });
|
|
202
|
+
let asset = null;
|
|
203
|
+
try {
|
|
204
|
+
const response = await fetch(this.releaseApi, { headers: { "user-agent": "dsh-containers-plugin" }, signal: AbortSignal.timeout(2e4) });
|
|
205
|
+
if (!response.ok) throw new Error(`发布 API 返回 HTTP ${response.status}`);
|
|
206
|
+
asset = pickMsiAsset((await response.json()).assets);
|
|
207
|
+
if (!asset) throw new Error("发布资产里没有找到 Windows MSI 安装包");
|
|
208
|
+
} catch (error) {
|
|
209
|
+
return { ok: false, stage: "resolve", message: `获取版本信息失败:${error.message}(可手动下载:https://github.com/libracoder/kiri/releases)` };
|
|
210
|
+
}
|
|
211
|
+
onProgress({ stage: "download", message: `下载 ${asset.name}…` });
|
|
212
|
+
let file = "";
|
|
213
|
+
try {
|
|
214
|
+
const dir = path2.join(os2.tmpdir(), "dsh-containers-setup");
|
|
215
|
+
await fs2.mkdir(dir, { recursive: true });
|
|
216
|
+
file = path2.join(dir, asset.name || "kiri-setup.msi");
|
|
217
|
+
const expected = Number(asset?.size) > 0 ? Number(asset.size) : 0;
|
|
218
|
+
let buffer = null;
|
|
219
|
+
for (let attempt = 1; attempt <= 3; attempt += 1) {
|
|
220
|
+
const response = await fetch(asset.browser_download_url, { signal: AbortSignal.timeout(6e5) });
|
|
221
|
+
if (!response.ok) throw new Error(`下载返回 HTTP ${response.status}`);
|
|
222
|
+
const total = Number(response.headers.get("content-length")) || expected;
|
|
223
|
+
const chunks = [];
|
|
224
|
+
let received = 0;
|
|
225
|
+
let reported = -1;
|
|
226
|
+
for await (const chunk of response.body) {
|
|
227
|
+
chunks.push(chunk);
|
|
228
|
+
received += chunk.length;
|
|
229
|
+
if (received - reported >= 262144 || received === total) {
|
|
230
|
+
reported = received;
|
|
231
|
+
const suffix = attempt > 1 ? `(第 ${attempt} 次尝试)` : "";
|
|
232
|
+
onProgress({ stage: "download", message: `${downloadProgressText(received, total)}${suffix}`, received, total });
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
const assembled = Buffer.concat(chunks);
|
|
236
|
+
if (total <= 0 || assembled.length === total) {
|
|
237
|
+
buffer = assembled;
|
|
238
|
+
break;
|
|
239
|
+
}
|
|
240
|
+
if (attempt === 3) throw new Error(`下载不完整(收到 ${(assembled.length / 1048576).toFixed(1)} MB,应为 ${(total / 1048576).toFixed(1)} MB,网络反复中断)`);
|
|
241
|
+
onProgress({ stage: "download", message: `下载中断,自动重试(第 ${attempt + 1} 次)…`, received: assembled.length, total });
|
|
242
|
+
}
|
|
243
|
+
await fs2.writeFile(file, buffer);
|
|
244
|
+
onProgress({ stage: "download", message: `已下载 ${(buffer.length / 1048576).toFixed(1)} MB`, received: buffer.length, total: buffer.length });
|
|
245
|
+
} catch (error) {
|
|
246
|
+
return { ok: false, stage: "download", message: `下载安装包失败:${error.message}(可手动下载:${asset.browser_download_url})` };
|
|
247
|
+
}
|
|
248
|
+
onProgress({ stage: "install", message: "静默安装中(per-user,无需管理员)…" });
|
|
249
|
+
try {
|
|
250
|
+
await new Promise((resolve, reject) => {
|
|
251
|
+
execFile2("msiexec", ["/i", file, "/qn", "/norestart"], { timeout: 6e5, windowsHide: true }, (error) => {
|
|
252
|
+
if (error) reject(new Error(`msiexec 退出码 ${error.code ?? "?"}(可能需要手动运行 ${file})`));
|
|
253
|
+
else resolve();
|
|
254
|
+
});
|
|
255
|
+
});
|
|
256
|
+
} catch (error) {
|
|
257
|
+
return { ok: false, stage: "install", message: `安装失败:${error.message}` };
|
|
258
|
+
}
|
|
259
|
+
onProgress({ stage: "verify", message: "重新探测 kiri…" });
|
|
260
|
+
const cli = await this.kiriCli.probe({ force: true });
|
|
261
|
+
let engineUp = false;
|
|
262
|
+
try {
|
|
263
|
+
await this.engine.detect({ force: true });
|
|
264
|
+
engineUp = true;
|
|
265
|
+
} catch {
|
|
266
|
+
}
|
|
267
|
+
return {
|
|
268
|
+
ok: true,
|
|
269
|
+
stage: "done",
|
|
270
|
+
message: engineUp ? `kiri 安装完成并已连接(${cli.version || "CLI 已就绪"})——面板已自动切换到 kiri` : `kiri 安装完成(${cli.version || "CLI 已就绪"});引擎首次启动需要一点时间,面板会自动重试连接`
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
};
|
|
274
|
+
|
|
275
|
+
// packages/dsh-containers-extras/src/host/extras.js
|
|
276
|
+
var ROUTES = {
|
|
277
|
+
k8s: "/api/dsh-containers/kiri/k8s",
|
|
278
|
+
machine: "/api/dsh-containers/kiri/machine",
|
|
279
|
+
setupKiri: "/api/dsh-containers/setup/kiri",
|
|
280
|
+
setupKiriStatus: "/api/dsh-containers/setup/kiri/status"
|
|
281
|
+
};
|
|
282
|
+
var Config = z.object({
|
|
283
|
+
releaseApi: z.string().default("https://api.github.com/repos/libracoder/kiri/releases/latest").description("kiri 发布信息 API;用于一键安装(下载官方 MSI 并静默安装)")
|
|
284
|
+
});
|
|
285
|
+
function tail(text, max = 2e3) {
|
|
286
|
+
const s = String(text || "").trim();
|
|
287
|
+
return s.length <= max ? s : `…${s.slice(-max)}`;
|
|
288
|
+
}
|
|
289
|
+
function freshSetupRun() {
|
|
290
|
+
return { phase: "idle", stage: "", message: "", received: 0, total: 0, ok: null, startedAt: 0, finishedAt: 0 };
|
|
291
|
+
}
|
|
292
|
+
var ContainersExtrasService = class extends Service {
|
|
293
|
+
/** @param {object} ctx 宿主上下文(inject 已含 kiri)@param {object} config 归一化配置。 */
|
|
294
|
+
constructor(ctx, config = {}) {
|
|
295
|
+
super(ctx, "containersExtras");
|
|
296
|
+
this.config = config;
|
|
297
|
+
this.containers = ctx.containers;
|
|
298
|
+
this.kiriCli = new KiriCli(config);
|
|
299
|
+
this.setup = new KiriSetup({ kiriCli: this.kiriCli, engine: this.containers.engine, config });
|
|
300
|
+
this.setupRun = freshSetupRun();
|
|
301
|
+
}
|
|
302
|
+
/** 启动 kiri 单节点 Kubernetes(k3s)。 */
|
|
303
|
+
async k8sStart() {
|
|
304
|
+
const result = await this.kiriCli.k8sStart();
|
|
305
|
+
return { ok: result.ok, missing: result.missing, output: tail(result.output), error: result.error };
|
|
306
|
+
}
|
|
307
|
+
/** 创建 kiri Linux 虚拟机。 */
|
|
308
|
+
async machineCreate(name, distro) {
|
|
309
|
+
const result = await this.kiriCli.machineCreate(name, distro);
|
|
310
|
+
return { ok: result.ok, missing: result.missing, output: tail(result.output), error: result.error };
|
|
311
|
+
}
|
|
312
|
+
/** Compose 操作(kiri CLI 文档子命令):up / down / ps / logs。 */
|
|
313
|
+
async compose(action, file, { detach = true } = {}) {
|
|
314
|
+
const target = String(file || "").trim();
|
|
315
|
+
if (!target) throw new Error("缺少 compose 文件路径");
|
|
316
|
+
if (!["up", "down", "ps", "logs"].includes(action)) throw new Error(`不支持的 compose 操作:${action}`);
|
|
317
|
+
const args = ["compose", "-f", target, action];
|
|
318
|
+
if (action === "up" && detach) args.push("-d");
|
|
319
|
+
if (action === "logs") args.push("--tail", "100");
|
|
320
|
+
const result = await this.kiriCli.run(args, { timeoutMs: action === "up" ? 6e5 : 12e4 });
|
|
321
|
+
return { ok: result.ok, missing: result.missing, output: tail(result.output), error: result.error };
|
|
322
|
+
}
|
|
323
|
+
/**
|
|
324
|
+
* 触发一键安装并立即返回状态快照(不等待完成):安装改在后台跑,
|
|
325
|
+
* 进度与结果写入 this.setupRun 供 setupStatus() 轮询。重复触发时
|
|
326
|
+
* 直接返回当前进度,不会双跑。
|
|
327
|
+
*/
|
|
328
|
+
installKiri() {
|
|
329
|
+
if (this.setupRun.phase === "running") {
|
|
330
|
+
return { ...this.setupRun, alreadyRunning: true };
|
|
331
|
+
}
|
|
332
|
+
const started = { ...freshSetupRun(), phase: "running", stage: "start", message: "准备安装…", startedAt: Date.now() };
|
|
333
|
+
this.setupRun = started;
|
|
334
|
+
void this.setup.installKiri({
|
|
335
|
+
onProgress: (progress) => {
|
|
336
|
+
if (this.setupRun !== started) return;
|
|
337
|
+
if (progress?.stage) this.setupRun.stage = String(progress.stage);
|
|
338
|
+
if (progress?.message) this.setupRun.message = String(progress.message);
|
|
339
|
+
if (Number.isFinite(progress?.received)) this.setupRun.received = progress.received;
|
|
340
|
+
if (Number.isFinite(progress?.total)) this.setupRun.total = progress.total;
|
|
341
|
+
}
|
|
342
|
+
}).then((result) => {
|
|
343
|
+
this.setupRun = {
|
|
344
|
+
...started,
|
|
345
|
+
phase: "done",
|
|
346
|
+
ok: Boolean(result?.ok),
|
|
347
|
+
stage: String(result?.stage || started.stage),
|
|
348
|
+
message: String(result?.message ?? ""),
|
|
349
|
+
finishedAt: Date.now()
|
|
350
|
+
};
|
|
351
|
+
}).catch((error) => {
|
|
352
|
+
this.setupRun = { ...started, phase: "done", ok: false, message: String(error?.message ?? error), finishedAt: Date.now() };
|
|
353
|
+
});
|
|
354
|
+
return { ...this.setupRun, started: true };
|
|
355
|
+
}
|
|
356
|
+
/** 当前安装状态快照(GET /setup/kiri/status 轮询用)。 */
|
|
357
|
+
setupStatus() {
|
|
358
|
+
return { ...this.setupRun };
|
|
359
|
+
}
|
|
360
|
+
};
|
|
361
|
+
function registerExtrasRoutes(ctx) {
|
|
362
|
+
const webServer = ctx.get("webServer");
|
|
363
|
+
if (!webServer || typeof webServer.register !== "function") return () => {
|
|
364
|
+
};
|
|
365
|
+
const getExtras = () => {
|
|
366
|
+
const extras = ctx.get("containersExtras");
|
|
367
|
+
if (!extras) throw new Error("containersExtras 服务尚未就绪,请稍后重试");
|
|
368
|
+
return extras;
|
|
369
|
+
};
|
|
370
|
+
const disposers = [];
|
|
371
|
+
const add = (path3, allowed, handler) => {
|
|
372
|
+
disposers.push(webServer.register({ kind: "exact", path: path3, handler: route(allowed, handler) }));
|
|
373
|
+
};
|
|
374
|
+
add(ROUTES.k8s, ["POST"], async (request, response) => {
|
|
375
|
+
await readJsonBody(request);
|
|
376
|
+
sendJson(response, 200, await getExtras().k8sStart(), request);
|
|
377
|
+
});
|
|
378
|
+
add(ROUTES.machine, ["POST"], async (request, response) => {
|
|
379
|
+
const payload = await readJsonBody(request);
|
|
380
|
+
const name = String(payload?.name || "").trim();
|
|
381
|
+
if (!name) {
|
|
382
|
+
sendJson(response, 400, { ok: false, error: "缺少虚拟机名称" }, request);
|
|
383
|
+
return;
|
|
384
|
+
}
|
|
385
|
+
sendJson(response, 200, await getExtras().machineCreate(name, payload?.distro), request);
|
|
386
|
+
});
|
|
387
|
+
add(ROUTES.setupKiri, ["POST"], async (request, response) => {
|
|
388
|
+
await readJsonBody(request);
|
|
389
|
+
sendJson(response, 200, { ok: true, run: getExtras().installKiri() }, request);
|
|
390
|
+
});
|
|
391
|
+
add(ROUTES.setupKiriStatus, ["GET"], async (request, response) => {
|
|
392
|
+
sendJson(response, 200, { ok: true, run: getExtras().setupStatus() }, request);
|
|
393
|
+
});
|
|
394
|
+
return () => {
|
|
395
|
+
for (const dispose of disposers) dispose();
|
|
396
|
+
};
|
|
397
|
+
}
|
|
398
|
+
var inject = ["containers", "webServer"];
|
|
399
|
+
function apply(ctx, config = {}) {
|
|
400
|
+
ctx.plugin(ContainersExtrasService, config);
|
|
401
|
+
const disposeRoutes = registerExtrasRoutes(ctx);
|
|
402
|
+
ctx.effect(() => () => disposeRoutes());
|
|
403
|
+
}
|
|
404
|
+
export {
|
|
405
|
+
Config,
|
|
406
|
+
ContainersExtrasService,
|
|
407
|
+
apply,
|
|
408
|
+
inject,
|
|
409
|
+
registerExtrasRoutes
|
|
410
|
+
};
|