@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.
@@ -0,0 +1,1080 @@
1
+ // packages/dsh-containers-core/shared/constants.js
2
+ var NS = "dsh-containers";
3
+ var BUILD = 4;
4
+
5
+ // packages/dsh-containers-core/src/host/service.js
6
+ import { Service } from "@deepseek-ai/cordis";
7
+
8
+ // packages/dsh-containers-core/src/host/kiri-cli.js
9
+ import { execFile } from "node:child_process";
10
+ import fs from "node:fs";
11
+ import os from "node:os";
12
+ import path from "node:path";
13
+ var PROBE_TTL_MS = 6e4;
14
+ var KiriCli = class {
15
+ /** @param {object} config 归一化配置(cliPath 等)。 */
16
+ constructor(config = {}) {
17
+ this.cliPath = config.cliPath || "kiri";
18
+ this.probeCache = null;
19
+ this.vmCache = null;
20
+ }
21
+ /** 执行一条 kiri 子命令;返回 { ok, code, output, error, missing },不抛错。 */
22
+ run(args, { timeoutMs = 3e4 } = {}) {
23
+ return new Promise((resolve) => {
24
+ execFile(
25
+ this.cliPath,
26
+ args,
27
+ { timeout: timeoutMs, windowsHide: true, maxBuffer: 4 * 1024 * 1024 },
28
+ (error, stdout, stderr) => {
29
+ const out = String(stdout || "");
30
+ const err = String(stderr || "");
31
+ if (error && error.code === "ENOENT") {
32
+ resolve({ ok: false, missing: true, code: null, output: "", error: `未找到 kiri CLI(${this.cliPath})` });
33
+ return;
34
+ }
35
+ if (error && !out && !err) {
36
+ resolve({ ok: false, missing: false, code: error.code ?? null, output: "", error: String(error.message) });
37
+ return;
38
+ }
39
+ resolve({ ok: error == null, missing: false, code: error?.code ?? 0, output: `${out}${err}`.trim(), error: null });
40
+ }
41
+ );
42
+ });
43
+ }
44
+ /** kiri CLI 可用性与版本;结果缓存 60 秒。 */
45
+ async probe({ force = false } = {}) {
46
+ if (this.probeCache && !force && Date.now() - this.probeCache.at < PROBE_TTL_MS) {
47
+ return this.probeCache.result;
48
+ }
49
+ let result = await this.run(["--version"], { timeoutMs: 5e3 });
50
+ if (!result.missing && !result.ok) {
51
+ result = await this.run(["version"], { timeoutMs: 5e3 });
52
+ }
53
+ 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 };
54
+ this.probeCache = { at: Date.now(), result: normalized };
55
+ return normalized;
56
+ }
57
+ /** ~/.kiri/vm.json(KIRI_DATA_DIR 可覆盖)里的虚拟机资源;读不到就返回 null。 */
58
+ vmConfig() {
59
+ if (this.vmCache && Date.now() - this.vmCache.at < PROBE_TTL_MS) return this.vmCache.value;
60
+ let value = null;
61
+ try {
62
+ const file = path.join(process.env.KIRI_DATA_DIR || path.join(os.homedir(), ".kiri"), "vm.json");
63
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
64
+ const pick = (raw) => Number.isFinite(Number(raw)) ? Number(raw) : void 0;
65
+ const cpus = pick(parsed?.cpus);
66
+ const memoryMiB = pick(parsed?.memoryMiB ?? parsed?.memory_mib);
67
+ if (cpus !== void 0 || memoryMiB !== void 0) value = { cpus, memoryMiB };
68
+ } catch {
69
+ value = null;
70
+ }
71
+ this.vmCache = { at: Date.now(), value };
72
+ return value;
73
+ }
74
+ /** 启动 kiri 单节点 Kubernetes(k3s,约 20 秒就绪,kubectl 上下文 kiri)。 */
75
+ k8sStart() {
76
+ return this.run(["k8s", "start"], { timeoutMs: 18e4 });
77
+ }
78
+ /** 创建 kiri Linux 虚拟机(kiri machine create <name> --distro <distro>)。 */
79
+ machineCreate(name, distro = "ubuntu") {
80
+ return this.run(["machine", "create", String(name), "--distro", String(distro || "ubuntu")], { timeoutMs: 3e5 });
81
+ }
82
+ };
83
+
84
+ // packages/dsh-containers-core/src/host/engine.js
85
+ import http from "node:http";
86
+ import os2 from "node:os";
87
+ import path2 from "node:path";
88
+ function autoCandidates() {
89
+ if (process.platform === "win32") {
90
+ return ["npipe://kiri", "npipe://docker_engine"];
91
+ }
92
+ return [
93
+ `unix://${path2.join(os2.homedir(), ".kiri/run/docker.sock")}`,
94
+ "unix:///var/run/docker.sock",
95
+ `unix://${path2.join(os2.homedir(), ".docker/run/docker.sock")}`
96
+ ];
97
+ }
98
+ function parseEndpoint(endpoint) {
99
+ const raw = String(endpoint || "").trim();
100
+ if (raw.startsWith("npipe://")) return { kind: "npipe", name: raw.slice("npipe://".length) };
101
+ if (/^\\\\.\\pipe\\/i.test(raw)) return { kind: "npipe", name: raw.slice("\\\\.\\pipe\\".length) };
102
+ if (raw.startsWith("unix://")) return { kind: "unix", path: raw.slice("unix://".length) };
103
+ if (raw.startsWith("tcp://")) {
104
+ const url = new URL(raw);
105
+ return { kind: "tcp", host: url.hostname || "127.0.0.1", port: Number(url.port) || 2375 };
106
+ }
107
+ return { kind: "unix", path: raw };
108
+ }
109
+ function engineLabel(endpoint) {
110
+ const s = String(endpoint).toLowerCase();
111
+ if (s.includes("kiri")) return "kiri";
112
+ if (s.includes("docker")) return "docker";
113
+ return "unknown";
114
+ }
115
+ function request(endpoint, method, urlPath, { query, body, timeoutMs = 1e4 } = {}) {
116
+ const parsed = parseEndpoint(endpoint);
117
+ const qs = query ? `?${new URLSearchParams(query).toString()}` : "";
118
+ const payload = body === void 0 || body === null ? null : Buffer.from(typeof body === "string" ? body : JSON.stringify(body), "utf8");
119
+ return new Promise((resolve, reject) => {
120
+ const req = http.request(
121
+ {
122
+ method,
123
+ path: urlPath + qs,
124
+ ...parsed.kind === "tcp" ? { host: parsed.host, port: parsed.port } : { socketPath: parsed.kind === "npipe" ? `\\\\.\\pipe\\${parsed.name}` : parsed.path },
125
+ headers: {
126
+ host: "docker",
127
+ ...payload ? { "content-type": "application/json", "content-length": payload.length } : {}
128
+ }
129
+ },
130
+ (res) => {
131
+ const chunks = [];
132
+ res.on("data", (chunk) => chunks.push(chunk));
133
+ res.on("end", () => resolve({ status: res.statusCode, headers: res.headers, body: Buffer.concat(chunks) }));
134
+ res.on("error", reject);
135
+ }
136
+ );
137
+ req.setTimeout(timeoutMs, () => req.destroy(new Error(`请求超时(${timeoutMs}ms):${method} ${urlPath}`)));
138
+ req.on("error", reject);
139
+ if (payload) req.write(payload);
140
+ req.end();
141
+ });
142
+ }
143
+ function jsonOrThrow(result, urlPath) {
144
+ const text = result.body.toString("utf8");
145
+ if (result.status >= 400) {
146
+ let message = text || `HTTP ${result.status}`;
147
+ try {
148
+ message = JSON.parse(text)?.message ?? message;
149
+ } catch {
150
+ }
151
+ const error = new Error(`Docker API ${result.status}(${urlPath}):${message}`);
152
+ error.status = result.status;
153
+ throw error;
154
+ }
155
+ if (!text) return null;
156
+ try {
157
+ return JSON.parse(text);
158
+ } catch {
159
+ return text;
160
+ }
161
+ }
162
+ function demuxFrames(buffer) {
163
+ const chunks = [];
164
+ let offset = 0;
165
+ while (buffer.length - offset >= 8) {
166
+ const size = buffer.readUInt32BE(offset + 4);
167
+ if (size > 16 * 1024 * 1024) {
168
+ chunks.push(buffer.subarray(offset));
169
+ return Buffer.concat(chunks).toString("utf8");
170
+ }
171
+ if (buffer.length - offset < 8 + size) break;
172
+ chunks.push(buffer.subarray(offset + 8, offset + 8 + size));
173
+ offset += 8 + size;
174
+ }
175
+ if (offset < buffer.length) chunks.push(buffer.subarray(offset));
176
+ return Buffer.concat(chunks).toString("utf8");
177
+ }
178
+ var CHOICES = ["auto", "kiri", "docker"];
179
+ function choiceEndpoint(choice) {
180
+ if (choice === "auto") return null;
181
+ return autoCandidates().find((endpoint) => engineLabel(endpoint) === choice) || null;
182
+ }
183
+ var Engine = class _Engine {
184
+ /** @param {object} config 已归一化的插件配置(Config schema 校验后)。 */
185
+ constructor(config = {}) {
186
+ this.configured = config.endpoint || "auto";
187
+ this.timeoutMs = config.requestTimeoutMs || 1e4;
188
+ this.choice = "auto";
189
+ this.detected = null;
190
+ }
191
+ /** 切换引擎:auto 跟随配置与自动探测;kiri / docker 固定到对应端点。仅本进程运行时状态,不改配置文件。 */
192
+ setChoice(choice) {
193
+ const normalized = String(choice ?? "auto").trim().toLowerCase();
194
+ if (!CHOICES.includes(normalized)) {
195
+ throw new Error("未知引擎选择:" + choice + "(可选 auto / kiri / docker)");
196
+ }
197
+ const endpoint = choiceEndpoint(normalized);
198
+ if (normalized !== "auto" && !endpoint) {
199
+ throw new Error("当前平台没有 " + normalized + " 对应的引擎端点");
200
+ }
201
+ this.choice = normalized;
202
+ this.detected = null;
203
+ }
204
+ /** 按配置与运行时选择列出待探测端点:运行时固定选择最优先,其次显式端点,auto 按优先级试全部。 */
205
+ endpoints() {
206
+ const forced = choiceEndpoint(this.choice);
207
+ if (forced) return [forced];
208
+ return this.configured === "auto" ? autoCandidates() : [this.configured];
209
+ }
210
+ /**
211
+ * 探测两个候选引擎的在线状态与版本(引擎切换菜单用)。
212
+ * 用独立的临时 Engine 实例探测,不影响主连接与缓存;失败一律按 offline 返回。
213
+ */
214
+ async probeEngines() {
215
+ const probe = async (choice) => {
216
+ const endpoint = choiceEndpoint(choice);
217
+ if (!endpoint) return { online: false, endpoint: "", version: "", apiVersion: "" };
218
+ try {
219
+ const candidate = new _Engine({ endpoint, requestTimeoutMs: 2e3 });
220
+ const info = await candidate.ping();
221
+ return { online: true, endpoint, version: info.version || "", apiVersion: info.apiVersion || "" };
222
+ } catch {
223
+ return { online: false, endpoint, version: "", apiVersion: "" };
224
+ }
225
+ };
226
+ const [kiri, docker] = await Promise.all([probe("kiri"), probe("docker")]);
227
+ return { kiri, docker };
228
+ }
229
+ /** 找到一个 /_ping 可达的端点并缓存;全部不可达时抛错。 */
230
+ async detect({ force = false } = {}) {
231
+ if (this.detected && !force) return this.detected;
232
+ this.detected = null;
233
+ for (const endpoint of this.endpoints()) {
234
+ try {
235
+ const result = await request(endpoint, "GET", "/_ping", { timeoutMs: 1500 });
236
+ if (result.status === 200 || result.status === 204) {
237
+ this.detected = { endpoint, label: engineLabel(endpoint) };
238
+ return this.detected;
239
+ }
240
+ } catch {
241
+ }
242
+ }
243
+ const forcedEndpoint = choiceEndpoint(this.choice);
244
+ if (forcedEndpoint) {
245
+ throw new Error("所选引擎(" + this.choice + ")不可达:" + forcedEndpoint);
246
+ }
247
+ throw new Error("未找到可用的容器引擎(kiri 管道 / docker_engine 管道 / unix socket 均不可达)");
248
+ }
249
+ /**
250
+ * 核心调用:探测 → 请求 → 传输层失败时强制重探一次再重试。
251
+ * HTTP 状态错误(4xx/5xx)是业务错误,直接上抛,不重试。
252
+ */
253
+ async call(method, urlPath, opts = {}) {
254
+ const { endpoint } = await this.detect();
255
+ try {
256
+ return await request(endpoint, method, urlPath, { timeoutMs: this.timeoutMs, ...opts });
257
+ } catch (error) {
258
+ if (error.status !== void 0) throw error;
259
+ this.detected = null;
260
+ const again = await this.detect();
261
+ return request(again.endpoint, method, urlPath, { timeoutMs: this.timeoutMs, ...opts });
262
+ }
263
+ }
264
+ async callJson(method, urlPath, opts = {}) {
265
+ return jsonOrThrow(await this.call(method, urlPath, opts), urlPath);
266
+ }
267
+ /* ---------------- 只读操作 ---------------- */
268
+ /** 引擎握手信息:标签、端点、版本。 */
269
+ async ping() {
270
+ const { endpoint, label } = await this.detect();
271
+ const result = await request(endpoint, "GET", "/_ping", { timeoutMs: 2e3 });
272
+ let version = null;
273
+ try {
274
+ version = jsonOrThrow(await request(endpoint, "GET", "/version", { timeoutMs: 2e3 }), "/version");
275
+ } catch {
276
+ }
277
+ return {
278
+ ok: true,
279
+ engineLabel: label,
280
+ endpoint,
281
+ apiVersion: result.headers["api-version"] || version?.ApiVersion || "",
282
+ version: version?.Version || ""
283
+ };
284
+ }
285
+ /** 容器列表(归一化:id / name / image / state / status / created / ports)。 */
286
+ async listContainers(all = true) {
287
+ const list = await this.callJson("GET", "/containers/json", { query: { all: all ? "1" : "0" } });
288
+ return (Array.isArray(list) ? list : []).map((item) => ({
289
+ id: String(item.Id || "").slice(0, 12),
290
+ fullId: String(item.Id || ""),
291
+ name: String(item.Names?.[0] || "").replace(/^\//, ""),
292
+ image: String(item.Image || ""),
293
+ state: String(item.State || ""),
294
+ status: String(item.Status || ""),
295
+ created: Number(item.Created || 0),
296
+ labels: item.Labels && typeof item.Labels === "object" ? item.Labels : {},
297
+ /* 卷挂载名:卷页用它统计「被哪些容器使用」。 */
298
+ mounts: Array.isArray(item.Mounts) ? item.Mounts.filter((mount) => mount?.Type === "volume" && mount?.Name).map((mount) => String(mount.Name)) : [],
299
+ ports: Array.isArray(item.Ports) ? item.Ports.filter((port) => port?.PrivatePort).map((port) => `${port.PublicPort ? `${port.IP || "0.0.0.0"}:${port.PublicPort}->` : ""}${port.PrivatePort}/${port.Type || "tcp"}`) : []
300
+ }));
301
+ }
302
+ /** 单容器详情(logs 判断 TTY、运行面板回显都用它)。 */
303
+ async inspectContainer(id) {
304
+ return this.callJson("GET", `/containers/${encodeURIComponent(id)}/json`);
305
+ }
306
+ /** 镜像列表(归一化:id / repo / tag / size / created)。 */
307
+ async listImages() {
308
+ const list = await this.callJson("GET", "/images/json");
309
+ return (Array.isArray(list) ? list : []).map((item) => {
310
+ const [repo = "<none>", tag = ""] = String(item.RepoTags?.[0] || ":").split(":");
311
+ return {
312
+ id: String(item.Id || "").replace(/^sha256:/, "").slice(0, 12),
313
+ fullId: String(item.Id || ""),
314
+ repo,
315
+ tag,
316
+ tags: Array.isArray(item.RepoTags) ? item.RepoTags : [],
317
+ size: Number(item.Size || 0),
318
+ created: Number(item.Created || 0),
319
+ inUse: Number(item.Containers || 0) > 0
320
+ };
321
+ });
322
+ }
323
+ /* ---------------- 镜像管理(Docker Desktop 对齐) ---------------- */
324
+ /** 读镜像元数据(暴露端口 / 默认命令),用于「运行新容器」的预填。 */
325
+ async inspectImage(ref) {
326
+ const name = String(ref || "").trim();
327
+ if (!name) throw new Error("缺少镜像名");
328
+ const data = await this.callJson("GET", `/images/${encodeURIComponent(name)}/json`);
329
+ const config = data?.Config && typeof data.Config === "object" ? data.Config : {};
330
+ const exposed = config.ExposedPorts && typeof config.ExposedPorts === "object" ? config.ExposedPorts : {};
331
+ return {
332
+ ok: true,
333
+ ref: name,
334
+ exposedPorts: Object.keys(exposed),
335
+ cmd: Array.isArray(config.Cmd) ? config.Cmd : [],
336
+ env: Array.isArray(config.Env) ? config.Env : []
337
+ };
338
+ }
339
+ /** 删除镜像(force = 强制删除正在被占用的镜像)。 */
340
+ async removeImage(id, { force = false } = {}) {
341
+ await this.callJson("DELETE", `/images/${encodeURIComponent(id)}`, { query: force ? { force: "1" } : void 0 });
342
+ return { ok: true, id };
343
+ }
344
+ /** 给镜像打一个新标签(docker tag)。 */
345
+ async tagImage(id, repo, tag = "latest") {
346
+ if (!repo) throw new Error("缺少目标镜像名");
347
+ await this.callJson("POST", `/images/${encodeURIComponent(id)}/tag`, {
348
+ query: { repo: String(repo), tag: String(tag || "latest") }
349
+ });
350
+ return { ok: true, id, ref: `${repo}:${tag || "latest"}` };
351
+ }
352
+ /** 清理悬空镜像;all = 连未被容器使用的全部镜像一起清(对齐 docker image prune -a)。 */
353
+ async pruneImages({ all = false } = {}) {
354
+ const result = await this.callJson("POST", "/images/prune", {
355
+ query: all ? { filters: JSON.stringify({ all: ["1"] }) } : void 0
356
+ });
357
+ return {
358
+ ok: true,
359
+ removed: Array.isArray(result?.ImagesDeleted) ? result.ImagesDeleted.filter(Boolean).length : 0,
360
+ spaceReclaimed: Number(result?.SpaceReclaimed || 0)
361
+ };
362
+ }
363
+ /** Docker Hub / 镜像仓库搜索(docker search)。 */
364
+ async searchImages(term, { limit = 10 } = {}) {
365
+ const query = String(term || "").trim();
366
+ if (!query) throw new Error("缺少搜索词");
367
+ const bounded = Math.min(25, Math.max(1, Number(limit) || 10));
368
+ const list = await this.callJson("GET", "/images/search", { query: { term: query, limit: String(bounded) } });
369
+ return (Array.isArray(list) ? list : []).map((item) => ({
370
+ name: String(item.name || ""),
371
+ description: String(item.description || ""),
372
+ stars: Number(item.star_count || 0),
373
+ official: item.is_official === true
374
+ }));
375
+ }
376
+ /** 磁盘概览(docker system df):镜像/容器/卷的数量与占用。 */
377
+ async systemDf() {
378
+ const data = await this.callJson("GET", "/system/df");
379
+ const sum = (list) => Array.isArray(list) ? list.reduce((acc, item) => acc + Number(item.Size || 0), 0) : 0;
380
+ return {
381
+ ok: true,
382
+ images: { count: Array.isArray(data?.Images) ? data.Images.length : 0, size: sum(data?.Images) },
383
+ containers: { count: Array.isArray(data?.Containers) ? data.Containers.length : 0, size: sum(data?.Containers) },
384
+ volumes: { count: Array.isArray(data?.Volumes) ? data.Volumes.length : 0, size: sum(data?.Volumes) },
385
+ layersSize: Number(data?.LayersSize || 0)
386
+ };
387
+ }
388
+ /** 单容器一次性资源快照(CPU% / 内存),对齐 Docker Desktop 仪表盘列。 */
389
+ async containerStats(id) {
390
+ const data = await this.callJson("GET", `/containers/${encodeURIComponent(id)}/stats`, { query: { stream: "false" } });
391
+ const cpuDelta = Number(data?.cpu_stats?.cpu_usage?.total_usage || 0) - Number(data?.precpu_stats?.cpu_usage?.total_usage || 0);
392
+ const systemDelta = Number(data?.cpu_stats?.system_cpu_usage || 0) - Number(data?.precpu_stats?.system_cpu_usage || 0);
393
+ const onlineCpus = Number(data?.cpu_stats?.online_cpus || data?.precpu_stats?.online_cpus || 1);
394
+ const cpuPercent = systemDelta > 0 ? cpuDelta / systemDelta * onlineCpus * 100 : 0;
395
+ const memUsage = Number(data?.memory_stats?.usage || 0);
396
+ const memLimit = Number(data?.memory_stats?.limit || 0);
397
+ return {
398
+ id: String(id).slice(0, 12),
399
+ cpuPercent,
400
+ memUsage,
401
+ memLimit,
402
+ memPercent: memLimit > 0 ? memUsage / memLimit * 100 : 0
403
+ };
404
+ }
405
+ /* ---------------- 卷管理(Docker Desktop 对齐) ---------------- */
406
+ /** 卷列表(归一化:name / driver / mountpoint / created)。 */
407
+ async listVolumes() {
408
+ const data = await this.callJson("GET", "/volumes");
409
+ return (Array.isArray(data?.Volumes) ? data.Volumes : []).map((item) => {
410
+ const usage = item.UsageData && typeof item.UsageData === "object" ? item.UsageData : null;
411
+ return {
412
+ name: String(item.Name || ""),
413
+ driver: String(item.Driver || ""),
414
+ mountpoint: String(item.Mountpoint || ""),
415
+ created: item.CreatedAt ? Date.parse(item.CreatedAt) / 1e3 : 0,
416
+ refCount: usage && Number.isFinite(Number(usage.RefCount)) ? Number(usage.RefCount) : null,
417
+ size: usage && Number.isFinite(Number(usage.Size)) ? Number(usage.Size) : 0
418
+ };
419
+ });
420
+ }
421
+ /** 创建卷(driver 缺省用引擎默认 local)。 */
422
+ async createVolume(name, driver) {
423
+ if (!name) throw new Error("缺少卷名称");
424
+ await this.callJson("POST", "/volumes/create", { body: { Name: String(name), Driver: driver ? String(driver) : void 0 } });
425
+ return { ok: true, name };
426
+ }
427
+ /** 删除卷(inUse 由引擎侧拒绝,无需预检)。 */
428
+ async removeVolume(name) {
429
+ if (!name) throw new Error("缺少卷名称");
430
+ await this.callJson("DELETE", `/volumes/${encodeURIComponent(name)}`);
431
+ return { ok: true, name };
432
+ }
433
+ /** 清理未被使用的卷。 */
434
+ async pruneVolumes() {
435
+ const result = await this.callJson("POST", "/volumes/prune");
436
+ return {
437
+ ok: true,
438
+ removed: Array.isArray(result?.VolumesDeleted) ? result.VolumesDeleted.filter(Boolean).length : 0,
439
+ spaceReclaimed: Number(result?.SpaceReclaimed || 0)
440
+ };
441
+ }
442
+ /* ---------------- 网络管理(Docker Desktop 对齐) ---------------- */
443
+ /** 网络列表(归一化:name / id / driver / scope / internal / containerCount)。 */
444
+ async listNetworks() {
445
+ const list = await this.callJson("GET", "/networks");
446
+ return (Array.isArray(list) ? list : []).map((item) => ({
447
+ id: String(item.Id || "").slice(0, 12),
448
+ name: String(item.Name || ""),
449
+ driver: String(item.Driver || ""),
450
+ scope: String(item.Scope || ""),
451
+ internal: item.Internal === true,
452
+ containerCount: item.Containers ? Object.keys(item.Containers).length : 0
453
+ }));
454
+ }
455
+ /** 创建网络(driver:bridge / overlay …)。 */
456
+ async createNetwork(name, { driver = "bridge" } = {}) {
457
+ if (!name) throw new Error("缺少网络名称");
458
+ await this.callJson("POST", "/networks/create", { body: { Name: String(name), Driver: String(driver || "bridge") } });
459
+ return { ok: true, name };
460
+ }
461
+ /** 删除网络(内置网络由引擎侧拒绝)。 */
462
+ async removeNetwork(id) {
463
+ if (!id) throw new Error("缺少网络 id");
464
+ await this.callJson("DELETE", `/networks/${encodeURIComponent(id)}`);
465
+ return { ok: true, id };
466
+ }
467
+ /* ---------------- 写操作 ---------------- */
468
+ /** 对容器执行动作;返回 { ok: true } 或上抛带原因的错误。 */
469
+ async containerAction(id, action) {
470
+ const target = encodeURIComponent(id);
471
+ switch (action) {
472
+ case "start":
473
+ await this.callJson("POST", `/containers/${target}/start`);
474
+ break;
475
+ case "stop":
476
+ case "restart":
477
+ await this.callJson("POST", `/containers/${target}/${action}`, { query: { t: "10" } });
478
+ break;
479
+ case "pause":
480
+ case "unpause":
481
+ case "kill":
482
+ await this.callJson("POST", `/containers/${target}/${action}`);
483
+ break;
484
+ case "remove":
485
+ await this.callJson("DELETE", `/containers/${target}`, { query: { v: "1", force: "1" } });
486
+ break;
487
+ default:
488
+ throw new Error(`未知动作:${action}`);
489
+ }
490
+ return { ok: true, action, id };
491
+ }
492
+ /** 容器日志:按 TTY 与否决定是否剥帧头,返回纯文本。 */
493
+ async containerLogs(id, tail) {
494
+ const target = encodeURIComponent(id);
495
+ const info = await this.inspectContainer(target);
496
+ const result = await this.call("GET", `/containers/${target}/logs`, {
497
+ query: { stdout: "1", stderr: "1", tail: String(Math.max(1, tail || 200)) },
498
+ timeoutMs: this.timeoutMs
499
+ });
500
+ if (result.status >= 400) return jsonOrThrow(result, "logs");
501
+ return info?.Config?.Tty ? result.body.toString("utf8") : demuxFrames(result.body);
502
+ }
503
+ /** 拉取镜像;收集进度行,结束时回传最后一条状态或错误。 */
504
+ async pullImage(ref, onProgress = () => {
505
+ }) {
506
+ const [name, tag] = String(ref || "").split(":");
507
+ if (!name) throw new Error("镜像引用不能为空");
508
+ const result = await this.call("POST", "/images/create", {
509
+ query: { fromImage: name, tag: tag || "latest" },
510
+ timeoutMs: Math.max(this.timeoutMs, 6e5)
511
+ });
512
+ const text = result.body.toString("utf8");
513
+ const lines = text.split(/\r?\n/).filter(Boolean);
514
+ let last = null;
515
+ let error = null;
516
+ for (const line of lines) {
517
+ try {
518
+ const event = JSON.parse(line);
519
+ if (event.error) error = event.error;
520
+ last = event.status || last;
521
+ onProgress(event);
522
+ } catch {
523
+ }
524
+ }
525
+ if (result.status >= 400 && !error) error = text || `HTTP ${result.status}`;
526
+ if (error) throw new Error(String(error));
527
+ return { ok: true, ref: `${name}:${tag || "latest"}`, status: last || "" };
528
+ }
529
+ /**
530
+ * 创建并启动一个容器(等价 docker run -d)。
531
+ * 镜像不存在(404)时自动先拉取再重试一次。
532
+ */
533
+ async runContainer(spec = {}) {
534
+ const image = String(spec.image || "").trim();
535
+ if (!image) throw new Error("缺少 image");
536
+ const exposed = {};
537
+ const bindings = {};
538
+ for (const raw of Array.isArray(spec.ports) ? spec.ports : []) {
539
+ const text = String(raw).trim();
540
+ const exposeOnly = /^(\d+)(?:\/(tcp|udp))?$/.exec(text);
541
+ if (exposeOnly) {
542
+ exposed[`${exposeOnly[1]}/${exposeOnly[2] || "tcp"}`] = {};
543
+ continue;
544
+ }
545
+ const match = /^(?:(\d+\.\d+\.\d+\.\d+):)?(\d+):(\d+)(?:\/(tcp|udp))?$/.exec(text);
546
+ if (!match) continue;
547
+ const [, hostIp, hostPort, containerPort, type = "tcp"] = match;
548
+ const key = `${containerPort}/${type}`;
549
+ exposed[key] = {};
550
+ bindings[key] = [{ HostIp: hostIp || "", HostPort: String(hostPort) }];
551
+ }
552
+ const binds = (Array.isArray(spec.volumes) ? spec.volumes : []).map((row) => ({
553
+ host: String(row?.host ?? row?.source ?? "").trim(),
554
+ container: String(row?.container ?? row?.target ?? "").trim()
555
+ })).filter((row) => row.host && row.container).map((row) => `${row.host}:${row.container}`);
556
+ const hostConfig = {};
557
+ if (Object.keys(bindings).length) hostConfig.PortBindings = bindings;
558
+ if (binds.length) hostConfig.Binds = binds;
559
+ const body = {
560
+ Image: image,
561
+ Cmd: Array.isArray(spec.cmd) ? spec.cmd : void 0,
562
+ Env: Array.isArray(spec.env) ? spec.env.map((entry) => String(entry)) : void 0,
563
+ ExposedPorts: Object.keys(exposed).length ? exposed : void 0,
564
+ HostConfig: Object.keys(hostConfig).length ? hostConfig : void 0,
565
+ AttachStdin: false,
566
+ AttachStdout: false,
567
+ AttachStderr: false
568
+ };
569
+ const create = async () => this.callJson("POST", "/containers/create", {
570
+ query: spec.name ? { name: String(spec.name) } : void 0,
571
+ body
572
+ });
573
+ let created;
574
+ try {
575
+ created = await create();
576
+ } catch (error) {
577
+ if (error.status !== 404) throw error;
578
+ await this.pullImage(image);
579
+ created = await create();
580
+ }
581
+ const id = String(created?.Id || "");
582
+ if (!id) throw new Error("创建容器失败:引擎没有返回容器 id");
583
+ await this.callJson("POST", `/containers/${encodeURIComponent(id)}/start`);
584
+ return { ok: true, id: id.slice(0, 12), name: spec.name || "" };
585
+ }
586
+ };
587
+
588
+ // packages/dsh-containers-core/src/host/engine-launcher.js
589
+ import { spawn as spawnChild } from "node:child_process";
590
+ import fs2 from "node:fs";
591
+ import path3 from "node:path";
592
+ var DEFAULT_TIMEOUT_MS = 9e4;
593
+ var FAILURE_COOLDOWN_MS = 6e4;
594
+ var PROBE_INTERVAL_MS = 1e3;
595
+ var FIRST_RUNTIME_SHARE = 0.6;
596
+ function kiriExePaths(env) {
597
+ const list = [];
598
+ if (env.LOCALAPPDATA) list.push(path3.join(env.LOCALAPPDATA, "Kiri", "kiri-win.exe"));
599
+ if (env.ProgramFiles) list.push(path3.join(env.ProgramFiles, "Kiri", "kiri-win.exe"));
600
+ if (env["ProgramFiles(x86)"]) list.push(path3.join(env["ProgramFiles(x86)"], "Kiri", "kiri-win.exe"));
601
+ if (env.ProgramW6432) list.push(path3.join(env.ProgramW6432, "Kiri", "kiri-win.exe"));
602
+ return list;
603
+ }
604
+ function dockerDesktopExePaths(env) {
605
+ const list = [];
606
+ if (env.ProgramFiles) list.push(path3.join(env.ProgramFiles, "Docker", "Docker", "Docker Desktop.exe"));
607
+ if (env.ProgramW6432) list.push(path3.join(env.ProgramW6432, "Docker", "Docker", "Docker Desktop.exe"));
608
+ return list;
609
+ }
610
+ function createEngineLauncher({
611
+ engine,
612
+ config = {},
613
+ platform = process.platform,
614
+ env = process.env,
615
+ spawnImpl = spawnChild,
616
+ fsImpl = fs2,
617
+ now = () => Date.now(),
618
+ delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
619
+ pollIntervalMs = PROBE_INTERVAL_MS
620
+ } = {}) {
621
+ const enabled = platform === "win32" && config.autoStartEngine !== false;
622
+ const timeoutMs = Number(config.engineStartTimeoutMs) > 0 ? Number(config.engineStartTimeoutMs) : DEFAULT_TIMEOUT_MS;
623
+ let starting = null;
624
+ let attempt = null;
625
+ let cooldownUntil2 = 0;
626
+ let lastError = "";
627
+ let lastRuntime = "";
628
+ function runtimeOrder() {
629
+ const choice = engine && engine.choice ? engine.choice : "auto";
630
+ if (choice === "kiri" || choice === "docker") return [choice];
631
+ return ["kiri", "docker"];
632
+ }
633
+ function commandsFor(runtime) {
634
+ if (runtime === "kiri") {
635
+ const exe = kiriExePaths(env).find((candidate) => {
636
+ try {
637
+ return fsImpl.existsSync(candidate);
638
+ } catch {
639
+ return false;
640
+ }
641
+ });
642
+ return exe ? [{ command: exe, args: ["--background"], label: "kiri" }] : [];
643
+ }
644
+ if (runtime === "docker") {
645
+ const exe = dockerDesktopExePaths(env).find((candidate) => {
646
+ try {
647
+ return fsImpl.existsSync(candidate);
648
+ } catch {
649
+ return false;
650
+ }
651
+ });
652
+ if (!exe) return [];
653
+ return [
654
+ { command: "docker", args: ["desktop", "start"], label: "Docker Desktop" },
655
+ { command: exe, args: [], label: "Docker Desktop" }
656
+ ];
657
+ }
658
+ return [];
659
+ }
660
+ function launch({ command, args }) {
661
+ return new Promise((resolve) => {
662
+ let settled = false;
663
+ const done = (result) => {
664
+ if (settled) return;
665
+ settled = true;
666
+ resolve(result);
667
+ };
668
+ try {
669
+ const child = spawnImpl(command, args, { detached: true, stdio: "ignore", windowsHide: true });
670
+ child.once("error", (error) => done({ ok: false, error: String(error?.message ?? error) }));
671
+ child.once("spawn", () => {
672
+ if (typeof child.unref === "function") child.unref();
673
+ done({ ok: true });
674
+ });
675
+ setTimeout(() => done({ ok: true }), 1500);
676
+ } catch (error) {
677
+ done({ ok: false, error: String(error?.message ?? error) });
678
+ }
679
+ });
680
+ }
681
+ async function waitReady(deadline) {
682
+ if (!engine) return true;
683
+ while (now() < deadline) {
684
+ try {
685
+ await engine.detect({ force: true });
686
+ return true;
687
+ } catch {
688
+ await delay(pollIntervalMs);
689
+ }
690
+ }
691
+ return false;
692
+ }
693
+ async function run(runtimes) {
694
+ const overallDeadline = now() + timeoutMs;
695
+ const errors = [];
696
+ for (let index = 0; index < runtimes.length; index += 1) {
697
+ const runtime = runtimes[index];
698
+ const commands = commandsFor(runtime);
699
+ if (commands.length === 0) {
700
+ errors.push(runtime + " 未安装");
701
+ continue;
702
+ }
703
+ if (starting) starting.runtime = runtime;
704
+ const remainingRuntimes = runtimes.length - index;
705
+ const budget = remainingRuntimes > 1 ? Math.floor((overallDeadline - now()) * FIRST_RUNTIME_SHARE) : overallDeadline - now();
706
+ const deadline = Math.min(overallDeadline, now() + Math.max(budget, 15e3));
707
+ for (let commandIndex = 0; commandIndex < commands.length; commandIndex += 1) {
708
+ const command = commands[commandIndex];
709
+ const left = commands.length - commandIndex;
710
+ const commandDeadline = Math.min(overallDeadline, now() + Math.max(Math.floor((deadline - now()) / left), 0));
711
+ const result = await launch(command);
712
+ if (!result.ok) {
713
+ errors.push(command.label + " 启动失败:" + result.error);
714
+ continue;
715
+ }
716
+ if (await waitReady(commandDeadline)) {
717
+ lastRuntime = runtime;
718
+ lastError = "";
719
+ return;
720
+ }
721
+ errors.push(command.label + " 启动超时");
722
+ if (now() >= overallDeadline) break;
723
+ }
724
+ if (now() >= overallDeadline) break;
725
+ }
726
+ lastError = errors.join(";") || "没有可启动的容器引擎";
727
+ cooldownUntil2 = now() + FAILURE_COOLDOWN_MS;
728
+ }
729
+ function ensure(options = {}) {
730
+ if (!enabled) return snapshot();
731
+ if (attempt) return snapshot();
732
+ if (now() < cooldownUntil2) return snapshot();
733
+ const requested = Array.isArray(options.runtimes) ? options.runtimes : runtimeOrder();
734
+ const runtimes = requested.filter((runtime) => commandsFor(runtime).length > 0);
735
+ if (runtimes.length === 0) {
736
+ lastError = "未找到 kiri 或 Docker Desktop 的安装位置";
737
+ cooldownUntil2 = now() + FAILURE_COOLDOWN_MS;
738
+ return snapshot();
739
+ }
740
+ starting = { runtimes, runtime: runtimes[0], startedAt: now() };
741
+ attempt = run(runtimes).catch((error) => {
742
+ lastError = String(error?.message ?? error);
743
+ }).finally(() => {
744
+ attempt = null;
745
+ starting = null;
746
+ });
747
+ return snapshot();
748
+ }
749
+ function installed(runtime) {
750
+ return commandsFor(runtime).length > 0;
751
+ }
752
+ function noteReady() {
753
+ lastError = "";
754
+ cooldownUntil2 = 0;
755
+ }
756
+ function snapshot() {
757
+ return {
758
+ /** 插件是否允许自动启动引擎(配置项 autoStartEngine,且平台支持)。 */
759
+ enabled,
760
+ /** 是否正在启动中(UI 据此显示「正在启动引擎…」)。 */
761
+ starting: Boolean(starting),
762
+ /** 正在启动的运行时:kiri | docker | ''。 */
763
+ startRuntime: starting ? starting.runtime : "",
764
+ /** 上一次启动失败的原因(成功或未尝试时为空)。 */
765
+ startError: lastError,
766
+ /** 最近一次成功拉起的运行时。 */
767
+ lastStartedRuntime: lastRuntime
768
+ };
769
+ }
770
+ return { ensure, installed, snapshot, noteReady, _internals: { commandsFor, runtimeOrder } };
771
+ }
772
+
773
+ // packages/dsh-containers-core/src/host/hub.js
774
+ var HUB_BASE = "https://hub.docker.com/v2";
775
+ var REQUEST_TIMEOUT_MS = 5e3;
776
+ var FAILURE_COOLDOWN_MS2 = 6e4;
777
+ var cooldownUntil = 0;
778
+ var lastFailure = "";
779
+ async function hubJson(pathname) {
780
+ if (Date.now() < cooldownUntil) throw new Error(lastFailure || "Docker Hub 暂不可用");
781
+ if (typeof fetch !== "function") throw new Error("当前运行时不支持 fetch");
782
+ const timeout = typeof AbortSignal !== "undefined" && typeof AbortSignal.timeout === "function" ? AbortSignal.timeout(REQUEST_TIMEOUT_MS) : void 0;
783
+ try {
784
+ const response = await fetch(`${HUB_BASE}${pathname}`, {
785
+ headers: { accept: "application/json", "user-agent": "dsh-containers" },
786
+ signal: timeout
787
+ });
788
+ if (!response.ok) throw new Error(`Docker Hub 返回 ${response.status}`);
789
+ return await response.json();
790
+ } catch (error) {
791
+ lastFailure = String(error?.message ?? error);
792
+ cooldownUntil = Date.now() + FAILURE_COOLDOWN_MS2;
793
+ throw error;
794
+ }
795
+ }
796
+ async function searchRepositories(term, { limit = 25 } = {}) {
797
+ const query = String(term || "").trim();
798
+ if (!query) throw new Error("缺少搜索词");
799
+ const bounded = Math.min(100, Math.max(1, Number(limit) || 25));
800
+ const data = await hubJson(`/search/repositories/?query=${encodeURIComponent(query)}&page_size=${bounded}`);
801
+ const list = Array.isArray(data?.results) ? data.results : [];
802
+ return list.map((item) => ({
803
+ name: String(item?.repo_name || "").trim(),
804
+ description: String(item?.short_description || "").trim(),
805
+ stars: Number(item?.star_count || 0),
806
+ pulls: Number(item?.pull_count || 0),
807
+ official: item?.is_official === true
808
+ })).filter((item) => item.name);
809
+ }
810
+ function repositoryPath(name) {
811
+ const raw = String(name || "").trim().replace(/^docker\.io\//i, "");
812
+ const withoutTag = raw.includes(":") ? raw.slice(0, raw.lastIndexOf(":")) : raw;
813
+ if (!withoutTag) throw new Error("缺少镜像名");
814
+ return withoutTag.includes("/") ? withoutTag : `library/${withoutTag}`;
815
+ }
816
+ async function listTags(name, { limit = 25 } = {}) {
817
+ const repo = repositoryPath(name);
818
+ const bounded = Math.min(100, Math.max(1, Number(limit) || 25));
819
+ const path4 = `/repositories/${repo.split("/").map(encodeURIComponent).join("/")}/tags/`;
820
+ const data = await hubJson(`${path4}?page_size=${bounded}&ordering=last_updated`);
821
+ const list = Array.isArray(data?.results) ? data.results : [];
822
+ return list.map((item) => String(item?.name || "")).filter(Boolean);
823
+ }
824
+
825
+ // packages/dsh-containers-core/src/host/service.js
826
+ var ContainersService = class extends Service {
827
+ /** @param {object} ctx 宿主上下文 @param {object} config 归一化配置(类插件由 ctx.plugin 传入)。 */
828
+ constructor(ctx, config = {}) {
829
+ super(ctx, "containers");
830
+ this.config = config;
831
+ this.engine = new Engine(config);
832
+ this.launcher = createEngineLauncher({ engine: this.engine, config });
833
+ this.kiriCli = new KiriCli(config);
834
+ }
835
+ /** 切换引擎(面板切换器与 containers_engine 工具共用):auto / kiri / docker,切换后立即返回新状态。 */
836
+ async selectEngine(choice) {
837
+ this.engine.setChoice(choice);
838
+ return this.status();
839
+ }
840
+ /**
841
+ * 引擎握手:永远返回 ok:true(引擎不在时以 connected:false 报告,面板据此画横幅)。
842
+ * poll / logTail 一并下发 —— 客户端的轮询节奏与日志行数都跟随宿主配置,
843
+ * 不在客户端再写一份默认值。
844
+ *
845
+ * kiri 是插件的核心:无论当前连到哪个引擎,status 都带 kiri 段
846
+ * (CLI 可用性/版本、虚拟机资源),面板的「kiri 功能」区据此渲染。
847
+ */
848
+ async status() {
849
+ const poll = this.config.pollIntervalMs ?? 5e3;
850
+ const logTail = this.config.logTail ?? 200;
851
+ const kiri = {
852
+ cli: await this.kiriCli.probe(),
853
+ vm: this.kiriCli.vmConfig()
854
+ };
855
+ const engineChoice = this.engine.choice || "auto";
856
+ const engines = await this.engine.probeEngines();
857
+ try {
858
+ let info = await this.engine.ping();
859
+ this.launcher.noteReady();
860
+ const preference = await this.preferKiri(info);
861
+ if (preference && preference.current === "kiri") info = await this.engine.ping();
862
+ return {
863
+ ok: true,
864
+ connected: true,
865
+ ...info,
866
+ starting: false,
867
+ kiriPending: Boolean(preference && preference.current !== "kiri" && preference.starting),
868
+ autoStartEngine: this.launcher.snapshot().enabled,
869
+ engineChoice,
870
+ engines,
871
+ kiri,
872
+ poll,
873
+ logTail,
874
+ build: BUILD
875
+ };
876
+ } catch (error) {
877
+ const launch = this.launcher.ensure();
878
+ return {
879
+ ok: true,
880
+ connected: false,
881
+ error: String(error?.message ?? error),
882
+ starting: launch.starting,
883
+ startRuntime: launch.startRuntime,
884
+ startError: launch.startError,
885
+ autoStartEngine: launch.enabled,
886
+ engineChoice,
887
+ engines,
888
+ kiri,
889
+ poll,
890
+ logTail,
891
+ build: BUILD
892
+ };
893
+ }
894
+ }
895
+ /**
896
+ * 工具调用的前置握手:面板靠轮询看到「启动中 → 已连接」的翻转,
897
+ * 而一次工具调用必须自己在同一次调用里等到结果,否则模型只会拿到连接拒绝。
898
+ *
899
+ * 引擎已在线时只做一次 ping(与 status 同源),不会额外拉起进程;
900
+ * 不在线时按需启动并轮询到超时(engineStartTimeoutMs)。
901
+ */
902
+ async ensureReady(options = {}) {
903
+ const timeoutMs = options.timeoutMs ?? this.config.engineStartTimeoutMs ?? 9e4;
904
+ const intervalMs = options.intervalMs ?? 1e3;
905
+ const sleep = this.delay || ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
906
+ try {
907
+ let info = await this.engine.ping();
908
+ this.launcher.noteReady();
909
+ const preference = await this.preferKiri(info, { waitMs: timeoutMs, intervalMs });
910
+ if (preference && preference.current === "kiri") info = await this.engine.ping();
911
+ return info;
912
+ } catch (firstError) {
913
+ const launch = this.launcher.ensure();
914
+ if (!launch.enabled) throw firstError;
915
+ const deadline = Date.now() + timeoutMs;
916
+ let last = firstError;
917
+ while (Date.now() < deadline) {
918
+ await sleep(intervalMs);
919
+ try {
920
+ const info = await this.engine.ping();
921
+ this.launcher.noteReady();
922
+ return info;
923
+ } catch (error) {
924
+ last = error;
925
+ }
926
+ }
927
+ const waited = Math.round(timeoutMs / 1e3);
928
+ throw new Error(`容器引擎未就绪(等待 ${waited} 秒):${String(last?.message ?? last)}`);
929
+ }
930
+ }
931
+ /**
932
+ * auto 模式优先 kiri —— 引入 kiri 就是为了性能,装在本机的 kiri 不被 Docker Desktop
933
+ * 顶掉。触发条件(全部满足才动手):
934
+ * · 引擎选择是 auto(显式选 kiri / docker 时完全听用户的);
935
+ * · 允许自动启动(autoStartEngine);
936
+ * · 本机装了 kiri(launcher.installed('kiri'));
937
+ * · 当前握手落到的不是 kiri。
938
+ * waitMs = 0:只点火,交给下一次轮询发现 kiri 已就绪并自动切换(面板场景);
939
+ * waitMs > 0:阻塞到 kiri 就绪或超时(工具调用场景,本次就要在 kiri 上执行)。
940
+ */
941
+ async preferKiri(info, { waitMs = 0, intervalMs = 1e3 } = {}) {
942
+ if ((this.engine.choice || "auto") !== "auto") return null;
943
+ if (!this.launcher.snapshot().enabled) return null;
944
+ if (typeof this.launcher.installed !== "function" || !this.launcher.installed("kiri")) return null;
945
+ if (!info) {
946
+ try {
947
+ info = await this.engine.ping();
948
+ } catch {
949
+ return null;
950
+ }
951
+ }
952
+ if (info.engineLabel === "kiri") return null;
953
+ const launch = this.launcher.ensure({ runtimes: ["kiri"] });
954
+ const result = { current: info.engineLabel, starting: Boolean(launch.starting), error: launch.startError || "" };
955
+ if (!result.starting || !waitMs) return result;
956
+ const sleep = this.delay || ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
957
+ const deadline = Date.now() + waitMs;
958
+ while (Date.now() < deadline) {
959
+ await sleep(intervalMs);
960
+ try {
961
+ const next = await this.engine.ping();
962
+ if (next.engineLabel === "kiri") {
963
+ this.launcher.noteReady();
964
+ return { current: "kiri", starting: false, error: "" };
965
+ }
966
+ } catch {
967
+ }
968
+ }
969
+ return result;
970
+ }
971
+ /** 容器列表,新的在前。 */
972
+ async containers(all = true) {
973
+ const list = await this.engine.listContainers(all);
974
+ return list.sort((a, b) => b.created - a.created);
975
+ }
976
+ /** 容器动作:start / stop / restart / pause / unpause / kill / remove。 */
977
+ async action(id, action) {
978
+ return this.engine.containerAction(id, action);
979
+ }
980
+ /** 容器日志(纯文本,行数由配置与入参共同约束)。 */
981
+ async logs(id, tail) {
982
+ return this.engine.containerLogs(id, tail ?? this.config.logTail ?? 200);
983
+ }
984
+ /** 镜像列表,新的在前。 */
985
+ async images() {
986
+ const list = await this.engine.listImages();
987
+ return list.sort((a, b) => b.created - a.created);
988
+ }
989
+ /** 拉取镜像(完成或失败后返回;进度回调可选)。 */
990
+ async pull(ref, onProgress) {
991
+ return this.engine.pullImage(ref, onProgress);
992
+ }
993
+ /** 创建并启动容器(镜像缺失自动先拉取)。 */
994
+ async run(spec) {
995
+ return this.engine.runContainer(spec);
996
+ }
997
+ /* ---------------- Docker Desktop 对齐:镜像 / 卷 / 网络 / 磁盘 / 资源 ---------------- */
998
+ /** 镜像操作:remove / tag / prune。 */
999
+ async imageAction(action, payload = {}) {
1000
+ if (action === "remove") return this.engine.removeImage(payload.id, { force: payload.force === true });
1001
+ if (action === "tag") return this.engine.tagImage(payload.id, payload.repo, payload.tag);
1002
+ if (action === "prune") return this.engine.pruneImages({ all: payload.all === true });
1003
+ throw new Error(`未知镜像操作:${action}`);
1004
+ }
1005
+ async searchImages(term, limit) {
1006
+ return this.engine.searchImages(term, { limit });
1007
+ }
1008
+ /**
1009
+ * 搜索镜像:优先问 Docker Hub(有下载量、描述更全),失败时回落到引擎的
1010
+ * /images/search(只有星标,没有下载量)。UI 只关心 results,source/error 用于提示。
1011
+ */
1012
+ async searchHubImages(term, limit) {
1013
+ const query = String(term || "").trim();
1014
+ if (!query) throw new Error("缺少搜索词");
1015
+ try {
1016
+ const results = await searchRepositories(query, { limit });
1017
+ return { results, source: "hub" };
1018
+ } catch (error) {
1019
+ const results = await this.engine.searchImages(query, { limit });
1020
+ return {
1021
+ results: results.map((item) => ({ ...item, pulls: null })),
1022
+ source: "engine",
1023
+ error: String(error?.message ?? error)
1024
+ };
1025
+ }
1026
+ }
1027
+ /** 结果行 Tag 下拉使用的标签列表;Hub 不可用时至少保留 latest。 */
1028
+ async imageTags(name, limit) {
1029
+ const repo = String(name || "").trim();
1030
+ if (!repo) throw new Error("缺少镜像名");
1031
+ try {
1032
+ const tags = await listTags(repo, { limit });
1033
+ return { tags: tags.length ? tags : ["latest"], source: "hub" };
1034
+ } catch (error) {
1035
+ return { tags: ["latest"], source: "fallback", error: String(error?.message ?? error) };
1036
+ }
1037
+ }
1038
+ async inspectImage(ref) {
1039
+ return this.engine.inspectImage(ref);
1040
+ }
1041
+ async systemDf() {
1042
+ return this.engine.systemDf();
1043
+ }
1044
+ /** 运行中容器的资源快照(CPU%/内存);失败的单个容器不拖垮整体。 */
1045
+ async runningStats(ids) {
1046
+ const settled = await Promise.allSettled(ids.map((id) => this.engine.containerStats(id)));
1047
+ return settled.filter((item) => item.status === "fulfilled").map((item) => item.value);
1048
+ }
1049
+ async volumes() {
1050
+ return this.engine.listVolumes();
1051
+ }
1052
+ async volumeAction(action, payload = {}) {
1053
+ if (action === "create") return this.engine.createVolume(payload.name, payload.driver);
1054
+ if (action === "remove") return this.engine.removeVolume(payload.name);
1055
+ if (action === "prune") return this.engine.pruneVolumes();
1056
+ throw new Error(`未知卷操作:${action}`);
1057
+ }
1058
+ async networks() {
1059
+ return this.engine.listNetworks();
1060
+ }
1061
+ async networkAction(action, payload = {}) {
1062
+ if (action === "create") return this.engine.createNetwork(payload.name, { driver: payload.driver });
1063
+ if (action === "remove") return this.engine.removeNetwork(payload.id);
1064
+ throw new Error(`未知网络操作:${action}`);
1065
+ }
1066
+ /* ---------------- kiri 专属能力 ---------------- */
1067
+ /** 当前引擎标签(kiri / docker / unknown);未探测到时为空。 */
1068
+ engineLabel() {
1069
+ return this.engine.detected?.label ?? "";
1070
+ }
1071
+ };
1072
+
1073
+ // packages/dsh-containers-core/src/host/index.js
1074
+ function apply(ctx, config = {}) {
1075
+ ctx.plugin(ContainersService, config);
1076
+ console.log(`[${NS}] 引擎能力已就绪(build ${BUILD},端点 ${config.endpoint || "auto"},服务已发布为 ctx.containers)`);
1077
+ }
1078
+ export {
1079
+ apply
1080
+ };