@luckylillia-dev/luckylillia 9.0.1 → 9.0.3

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,1859 @@
1
+ import { A as Registries, Ft as resolveInstance, G as GATEWAY_SECRET_HEADER, Gt as LOG_DIR, H as GATEWAY_INSTANCE_HEADER, Ht as isDockerEnvironment, It as DEFAULT_INSTANCE, K as MANAGED_ENV, Kt as STATE_DIR, Lt as INVALID_INSTANCE_NAME, R as lockManager, Rt as isValidInstanceName, U as GATEWAY_PREFIX_HEADER, V as GATEWAY_AUTH_HEADER, W as GATEWAY_SECRET_ENV, Wt as DATA_DIR, a as scheduleAutoCheck, i as installDirOf, jt as configPaths, l as registriesOf, n as CoreUpdater, o as updateBlocker, ot as migrateToInstances, q as isInstanceMessage, s as MarketSchema, st as migrateWebuiToken, t as CoreUpdateError, z as runningInstances } from "./chunks/coreUpdate-FeEAjxU_.js";
2
+ import { n as isSupervised, r as parentPidOf, t as SUPERVISED_ENV } from "./chunks/restart-TVy8kurW.js";
3
+ import { appendFileSync, createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
4
+ import path from "node:path";
5
+ import { fork } from "node:child_process";
6
+ import { networkInterfaces } from "node:os";
7
+ import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
8
+ import http from "node:http";
9
+ //#region src/main/manager/gateway.ts
10
+ /** The cookie that remembers which instance a tab last opened, for requests that name none */
11
+ var INSTANCE_COOKIE = "llbot_instance";
12
+ var HOP_BY_HOP = /* @__PURE__ */ new Set([
13
+ "connection",
14
+ "keep-alive",
15
+ "proxy-authenticate",
16
+ "proxy-authorization",
17
+ "proxy-connection",
18
+ "te",
19
+ "trailer",
20
+ "transfer-encoding",
21
+ "upgrade"
22
+ ]);
23
+ var MAX_JSON_BODY = 65536;
24
+ /** `/i/<instance>/...` */
25
+ var PREFIXED = /^\/i\/([^/]+)(\/.*)?$/;
26
+ /**
27
+ * Which instance a request is for: the one its path names (`/i/<name>/...`), else the one of the page that made it
28
+ * (Referer: a plugin module importing or fetching a root path), else the one the tab last opened, else the default.
29
+ */
30
+ function routeOf(pathname, headers, fallback) {
31
+ const match = PREFIXED.exec(pathname);
32
+ if (match) {
33
+ let name;
34
+ try {
35
+ name = decodeURIComponent(match[1]);
36
+ } catch {
37
+ return;
38
+ }
39
+ if (!isValidInstanceName(name)) return void 0;
40
+ if (match[2] === void 0) return "redirect";
41
+ return {
42
+ instance: name,
43
+ prefix: `/i/${match[1]}`,
44
+ path: match[2]
45
+ };
46
+ }
47
+ const referer = headers.referer;
48
+ if (referer) try {
49
+ const fromReferer = PREFIXED.exec(new URL(referer).pathname);
50
+ const name = fromReferer && decodeURIComponent(fromReferer[1]);
51
+ if (name && isValidInstanceName(name) && fromReferer[2] !== void 0) return {
52
+ instance: name,
53
+ prefix: "",
54
+ path: pathname
55
+ };
56
+ } catch {}
57
+ const remembered = cookieOf(headers, INSTANCE_COOKIE);
58
+ if (remembered && isValidInstanceName(remembered)) return {
59
+ instance: remembered,
60
+ prefix: "",
61
+ path: pathname
62
+ };
63
+ return {
64
+ instance: fallback,
65
+ prefix: "",
66
+ path: pathname
67
+ };
68
+ }
69
+ function cookieOf(headers, name) {
70
+ for (const part of (headers.cookie ?? "").split(";")) {
71
+ const index = part.indexOf("=");
72
+ if (index < 0) continue;
73
+ if (part.slice(0, index).trim() === name) try {
74
+ return decodeURIComponent(part.slice(index + 1).trim());
75
+ } catch {
76
+ return part.slice(index + 1).trim();
77
+ }
78
+ }
79
+ }
80
+ /** The login cookie the WebUI keeps: named after the port the browser used (FE/utils/api.ts tokenCookieName) */
81
+ function loginCookieName(headers, secure) {
82
+ return `webui_token_${/:(\d+)$/.exec(headers.host ?? "")?.[1] ?? (secure ? "443" : "80")}`;
83
+ }
84
+ /**
85
+ * The one WebUI address of all instances: checks the login once and forwards each request to the instance it is
86
+ * for, on 127.0.0.1, with the gateway's secret. Streams both ways, so server-sent events and large uploads pass as
87
+ * they are.
88
+ */
89
+ var Gateway = class {
90
+ options;
91
+ server;
92
+ agent = new http.Agent({ keepAlive: true });
93
+ sockets = /* @__PURE__ */ new Set();
94
+ constructor(options) {
95
+ this.options = options;
96
+ this.server = http.createServer((request, response) => {
97
+ this.handle(request, response).catch((error) => {
98
+ this.options.log?.warn(`网关处理 ${request.method} ${request.url} 出错:${error.message}`);
99
+ if (!response.headersSent) json(response, 500, {
100
+ success: false,
101
+ message: "网关内部错误"
102
+ });
103
+ else response.destroy();
104
+ });
105
+ });
106
+ this.server.requestTimeout = 0;
107
+ this.server.on("connection", (socket) => {
108
+ this.sockets.add(socket);
109
+ socket.once("close", () => this.sockets.delete(socket));
110
+ });
111
+ }
112
+ /** Listens on `port`, else the next free one of the 100 after it; resolves to the port */
113
+ async listen(host, port) {
114
+ for (let candidate = port; candidate < port + 100 && candidate <= 65535; candidate++) {
115
+ const error = await new Promise((resolve) => {
116
+ const onError = (error) => resolve(error);
117
+ this.server.once("error", onError);
118
+ this.server.listen(candidate, host || void 0, () => {
119
+ this.server.off("error", onError);
120
+ resolve(void 0);
121
+ });
122
+ });
123
+ if (!error) {
124
+ const address = this.server.address();
125
+ return typeof address === "object" && address ? address.port : candidate;
126
+ }
127
+ if (error.code !== "EADDRINUSE") throw error;
128
+ if (candidate === port) this.options.log?.warn(`端口 ${port} 已被占用,尝试后面的端口`);
129
+ }
130
+ throw new Error(`端口 ${port} 到 ${port + 99} 都被占用了`);
131
+ }
132
+ async close() {
133
+ await this.closeServer();
134
+ this.agent.destroy();
135
+ }
136
+ /** Moves the listener to a new host / port while keeping the gateway and upstream pool alive */
137
+ async rebind(host, port) {
138
+ await this.closeServer();
139
+ return await this.listen(host, port);
140
+ }
141
+ async closeServer() {
142
+ if (!this.server.listening) return;
143
+ await new Promise((resolve) => {
144
+ this.server.close(() => resolve());
145
+ for (const socket of this.sockets) socket.destroy();
146
+ });
147
+ }
148
+ async handle(request, response) {
149
+ const url = new URL(request.url ?? "/", "http://gateway");
150
+ const route = routeOf(url.pathname, request.headers, this.options.defaultInstance());
151
+ if (route === "redirect") {
152
+ response.writeHead(302, { location: `${url.pathname}/${url.search}` });
153
+ response.end();
154
+ return;
155
+ }
156
+ if (!route) {
157
+ text(response, 404, "没有这个实例");
158
+ return;
159
+ }
160
+ const ip = request.socket.remoteAddress ?? "";
161
+ const method = request.method ?? "GET";
162
+ const presented = headerOf(request, "x-webui-token") || url.searchParams.get("token") || void 0;
163
+ if (route.path === "/api/set-token") {
164
+ await this.setToken(request, response, presented, ip, url.pathname);
165
+ return;
166
+ }
167
+ if (route.path === "/api/manager" || route.path.startsWith("/api/manager/")) {
168
+ const refusal = this.options.auth.check(presented, ip, method, url.pathname);
169
+ if (refusal) return refuse(response, refusal);
170
+ if (!await this.options.manager?.(request, response, route.path)) json(response, 404, {
171
+ success: false,
172
+ message: "接口不存在"
173
+ });
174
+ return;
175
+ }
176
+ if (this.options.coreUpdate && (route.path === "/api/core-update" || route.path.startsWith("/api/core-update/"))) {
177
+ const refusal = this.options.auth.check(presented, ip, method, url.pathname);
178
+ if (refusal) return refuse(response, refusal);
179
+ if (!await this.options.coreUpdate(request, response, route.path, url.searchParams)) json(response, 404, {
180
+ success: false,
181
+ message: "接口不存在"
182
+ });
183
+ return;
184
+ }
185
+ if (this.options.webuiDir && (method === "GET" || method === "HEAD")) {
186
+ const staticPath = route.prefix ? route.path : url.pathname;
187
+ const extraHeaders = {};
188
+ if (route.prefix && isDocument(request) && this.options.lookup(route.instance)) extraHeaders["set-cookie"] = `${INSTANCE_COOKIE}=${encodeURIComponent(route.instance)}; Path=/; SameSite=Lax`;
189
+ if (this.serveStatic(response, staticPath, method === "HEAD", extraHeaders)) return;
190
+ }
191
+ let authenticated = false;
192
+ if (route.path.startsWith("/api/")) {
193
+ const refusal = this.options.auth.check(presented, ip, method, url.pathname);
194
+ if (refusal) return refuse(response, refusal);
195
+ authenticated = true;
196
+ } else if (route.path.startsWith("/plugin-webui/") || route.path.startsWith("/plugin-assets/")) {
197
+ const secure = request.headers["x-forwarded-proto"] === "https";
198
+ if (this.options.auth.check(cookieOf(request.headers, loginCookieName(request.headers, secure)), ip, method, url.pathname)) {
199
+ response.writeHead(401);
200
+ response.end();
201
+ return;
202
+ }
203
+ authenticated = true;
204
+ } else {
205
+ const secure = request.headers["x-forwarded-proto"] === "https";
206
+ authenticated = this.options.auth.matches(presented ?? cookieOf(request.headers, loginCookieName(request.headers, secure)));
207
+ }
208
+ const target = this.options.lookup(route.instance);
209
+ if (!target) {
210
+ if (route.path.startsWith("/api/")) json(response, 404, {
211
+ success: false,
212
+ message: `没有实例 ${route.instance}`
213
+ });
214
+ else text(response, 404, `没有实例 ${route.instance}`);
215
+ return;
216
+ }
217
+ if (!target.port) {
218
+ unavailable(response, target, route.path);
219
+ return;
220
+ }
221
+ this.forward(request, response, url, route, target.port, authenticated);
222
+ }
223
+ forward(request, response, url, route, port, authenticated) {
224
+ url.searchParams.delete("token");
225
+ const headers = {};
226
+ for (const [name, value] of Object.entries(request.headers)) {
227
+ if (value === void 0 || HOP_BY_HOP.has(name) || name.startsWith("x-llbot-") || name === "x-webui-token") continue;
228
+ if (name === "x-forwarded-for" || name === "x-forwarded-proto" || name === "x-forwarded-host" || name === "x-forwarded-prefix") continue;
229
+ headers[name] = value;
230
+ }
231
+ const cookie = (request.headers.cookie ?? "").split(";").filter((part) => !part.trim().startsWith("webui_token_")).join(";").trim();
232
+ if (cookie) headers.cookie = cookie;
233
+ else delete headers.cookie;
234
+ headers["x-forwarded-for"] = [request.headers["x-forwarded-for"], request.socket.remoteAddress].flat().filter(Boolean).join(", ");
235
+ headers["x-forwarded-proto"] = headerOf(request, "x-forwarded-proto") || "http";
236
+ if (request.headers.host) headers["x-forwarded-host"] = request.headers.host;
237
+ headers[GATEWAY_PREFIX_HEADER] = route.prefix;
238
+ headers[GATEWAY_INSTANCE_HEADER] = route.instance;
239
+ headers[GATEWAY_SECRET_HEADER] = this.options.secret;
240
+ if (authenticated) headers[GATEWAY_AUTH_HEADER] = "ok";
241
+ const upstream = http.request({
242
+ host: "127.0.0.1",
243
+ port,
244
+ method: request.method,
245
+ path: route.path + url.search,
246
+ headers,
247
+ agent: this.agent
248
+ }, (upstreamResponse) => {
249
+ const out = {};
250
+ for (const [name, value] of Object.entries(upstreamResponse.headers)) {
251
+ if (value === void 0 || HOP_BY_HOP.has(name)) continue;
252
+ out[name] = value;
253
+ }
254
+ if (route.prefix && isDocument(request)) {
255
+ const remember = `${INSTANCE_COOKIE}=${encodeURIComponent(route.instance)}; Path=/; SameSite=Lax`;
256
+ const existing = out["set-cookie"];
257
+ out["set-cookie"] = [...Array.isArray(existing) ? existing : existing ? [String(existing)] : [], remember];
258
+ out["cache-control"] = "no-store";
259
+ delete out["last-modified"];
260
+ delete out.etag;
261
+ }
262
+ response.writeHead(upstreamResponse.statusCode ?? 502, upstreamResponse.statusMessage, out);
263
+ if (String(upstreamResponse.headers["content-type"] ?? "").startsWith("text/event-stream")) response.flushHeaders();
264
+ upstreamResponse.pipe(response);
265
+ });
266
+ upstream.on("error", (error) => {
267
+ if (!response.headersSent) {
268
+ if (route.path.startsWith("/api/")) json(response, 502, {
269
+ success: false,
270
+ message: `实例 ${route.instance} 没有响应:${error.message}`
271
+ });
272
+ else text(response, 502, `实例 ${route.instance} 没有响应:${error.message}`);
273
+ } else response.destroy();
274
+ });
275
+ response.once("close", () => {
276
+ if (!response.writableFinished) upstream.destroy();
277
+ });
278
+ request.pipe(upstream);
279
+ }
280
+ async setToken(request, response, presented, ip, url) {
281
+ if (request.method !== "POST") return json(response, 405, {
282
+ success: false,
283
+ message: "只接受 POST"
284
+ });
285
+ if (this.options.auth.getToken()) {
286
+ const refusal = this.options.auth.check(presented, ip, "POST", url);
287
+ if (refusal) return refuse(response, refusal);
288
+ }
289
+ let token;
290
+ try {
291
+ token = JSON.parse(await readBody(request)).token;
292
+ } catch {
293
+ return json(response, 400, {
294
+ success: false,
295
+ message: "请求格式不对"
296
+ });
297
+ }
298
+ if (typeof token !== "string" || !token.trim()) return json(response, 400, {
299
+ success: false,
300
+ message: "Token不能为空"
301
+ });
302
+ this.options.auth.setToken(token);
303
+ json(response, 200, {
304
+ success: true,
305
+ message: "Token设置成功"
306
+ });
307
+ }
308
+ serveStatic(response, pathname, headOnly, extraHeaders = {}) {
309
+ if (pathname.startsWith("/api/") || pathname.startsWith("/plugin-webui/") || pathname.startsWith("/plugin-assets/")) return false;
310
+ const root = path.resolve(this.options.webuiDir);
311
+ let decoded;
312
+ try {
313
+ decoded = decodeURIComponent(pathname);
314
+ } catch {
315
+ return false;
316
+ }
317
+ if (decoded.includes("\0")) return false;
318
+ const relative = decoded === "/" ? "/index.html" : decoded;
319
+ const file = path.resolve(root, "." + relative);
320
+ if (file !== root && !file.startsWith(root + path.sep)) return false;
321
+ let stat;
322
+ try {
323
+ stat = statSync(file);
324
+ } catch {
325
+ return false;
326
+ }
327
+ if (!stat.isFile()) return false;
328
+ const ext = path.extname(file).toLowerCase();
329
+ const isHtml = ext === ".html";
330
+ const isHashedAsset = relative.startsWith("/assets/");
331
+ response.writeHead(200, {
332
+ ...extraHeaders,
333
+ "content-type": MIME_TYPES[ext] ?? "application/octet-stream",
334
+ "content-length": stat.size,
335
+ "cache-control": isHtml ? "no-store" : isHashedAsset ? "public, max-age=31536000, immutable" : "public, max-age=3600"
336
+ });
337
+ if (headOnly) {
338
+ response.end();
339
+ return true;
340
+ }
341
+ const stream = createReadStream(file);
342
+ stream.on("error", () => {
343
+ if (!response.headersSent) response.writeHead(500);
344
+ response.destroy();
345
+ });
346
+ stream.pipe(response);
347
+ return true;
348
+ }
349
+ };
350
+ var MIME_TYPES = {
351
+ ".html": "text/html; charset=utf-8",
352
+ ".js": "text/javascript; charset=utf-8",
353
+ ".mjs": "text/javascript; charset=utf-8",
354
+ ".css": "text/css; charset=utf-8",
355
+ ".json": "application/json; charset=utf-8",
356
+ ".svg": "image/svg+xml",
357
+ ".png": "image/png",
358
+ ".jpg": "image/jpeg",
359
+ ".jpeg": "image/jpeg",
360
+ ".webp": "image/webp",
361
+ ".gif": "image/gif",
362
+ ".ico": "image/x-icon",
363
+ ".woff": "font/woff",
364
+ ".woff2": "font/woff2",
365
+ ".ttf": "font/ttf",
366
+ ".txt": "text/plain; charset=utf-8",
367
+ ".map": "application/json; charset=utf-8"
368
+ };
369
+ function headerOf(request, name) {
370
+ const value = request.headers[name];
371
+ return Array.isArray(value) ? value[0] : value;
372
+ }
373
+ function isDocument(request) {
374
+ const destination = request.headers["sec-fetch-dest"];
375
+ if (destination) return destination === "document" || destination === "iframe";
376
+ return request.method === "GET" && String(request.headers.accept ?? "").includes("text/html");
377
+ }
378
+ function refuse(response, refusal) {
379
+ json(response, refusal.status, refusal.body, { "x-webui-auth": refusal.reason });
380
+ }
381
+ function json(response, status, body, headers = {}) {
382
+ const data = JSON.stringify(body);
383
+ response.writeHead(status, {
384
+ "content-type": "application/json; charset=utf-8",
385
+ "content-length": Buffer.byteLength(data),
386
+ ...headers
387
+ });
388
+ response.end(data);
389
+ }
390
+ function text(response, status, message) {
391
+ response.writeHead(status, { "content-type": "text/plain; charset=utf-8" });
392
+ response.end(message);
393
+ }
394
+ var PHASE_TEXT = {
395
+ stopped: "已停止",
396
+ starting: "正在启动",
397
+ running: "正在启动",
398
+ stopping: "正在停止",
399
+ failed: "启动失败"
400
+ };
401
+ function unavailable(response, target, path) {
402
+ const state = PHASE_TEXT[target.phase];
403
+ if (path.startsWith("/api/")) {
404
+ json(response, 503, {
405
+ success: false,
406
+ message: `实例 ${target.name} ${state}`,
407
+ data: {
408
+ instance: target.name,
409
+ phase: target.phase
410
+ }
411
+ });
412
+ return;
413
+ }
414
+ const waiting = target.phase === "starting" || target.phase === "running";
415
+ const name = escapeHtml(target.name);
416
+ response.writeHead(503, {
417
+ "content-type": "text/html; charset=utf-8",
418
+ "cache-control": "no-store",
419
+ ...waiting ? { refresh: "2" } : {}
420
+ });
421
+ response.end(`<!doctype html><meta charset="utf-8"><title>LuckyLillia</title>
422
+ <body style="font-family:system-ui,sans-serif;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;color:#555">
423
+ <div style="text-align:center"><h2>实例 ${name} ${state}</h2>
424
+ <p>${waiting ? "页面会在实例启动后自动打开" : "请在实例管理中启动它"}</p>
425
+ <p style="margin-top:16px"><a href="/" style="color:#ec4899;text-decoration:none;font-weight:500">返回实例管理</a></p></div></body>`);
426
+ }
427
+ function escapeHtml(value) {
428
+ return value.replace(/[&<>"']/g, (c) => ({
429
+ "&": "&amp;",
430
+ "<": "&lt;",
431
+ ">": "&gt;",
432
+ "\"": "&quot;",
433
+ "'": "&#39;"
434
+ })[c]);
435
+ }
436
+ function readBody(request, limit = MAX_JSON_BODY) {
437
+ return new Promise((resolve, reject) => {
438
+ let size = 0;
439
+ const chunks = [];
440
+ request.on("data", (chunk) => {
441
+ size += chunk.length;
442
+ if (size > limit) {
443
+ reject(/* @__PURE__ */ new Error("请求体太大"));
444
+ request.destroy();
445
+ return;
446
+ }
447
+ chunks.push(chunk);
448
+ });
449
+ request.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
450
+ request.on("error", reject);
451
+ });
452
+ }
453
+ //#endregion
454
+ //#region src/main/manager/registry.ts
455
+ var DEFAULT_GATEWAY_HOST = "127.0.0.1";
456
+ var DEFAULT_GATEWAY_PORT = 3080;
457
+ /**
458
+ * The instances of a data directory and the manager's settings. An instance is a directory under
459
+ * data/instances/; data/manager.json only adds what the manager needs to know about it.
460
+ */
461
+ var Registry = class {
462
+ dataDir;
463
+ log;
464
+ file;
465
+ instancesDir;
466
+ config;
467
+ constructor(dataDir, log) {
468
+ this.dataDir = dataDir;
469
+ this.log = log;
470
+ this.file = path.join(dataDir, "manager.json");
471
+ this.instancesDir = path.join(dataDir, "instances");
472
+ }
473
+ /**
474
+ * Reads data/manager.json, writing it on the first start: the gateway takes the address the default instance's
475
+ * WebUI had, so the WebUI keeps its URL. On a brand-new directory with no instances yet, seeds `default`.
476
+ */
477
+ load() {
478
+ if (this.config) return this.config;
479
+ let saved;
480
+ const hasFile = existsSync(this.file);
481
+ if (hasFile) try {
482
+ saved = JSON.parse(readFileSync(this.file, "utf8"));
483
+ } catch (error) {
484
+ this.log.warn(`${this.file} 不是有效的 JSON,本次使用默认设置:${error.message}`);
485
+ const disk = this.diskInstances();
486
+ this.config = normalize(void 0, disk, this.legacyGateway());
487
+ return this.config;
488
+ }
489
+ let disk = this.diskInstances();
490
+ if (!hasFile && disk.length === 0) {
491
+ mkdirSync(path.join(this.instancesDir, DEFAULT_INSTANCE), { recursive: true });
492
+ disk = [DEFAULT_INSTANCE];
493
+ }
494
+ this.config = normalize(saved, disk, saved ? void 0 : this.legacyGateway());
495
+ if (!hasFile) {
496
+ this.save();
497
+ this.log.info(`已创建 ${this.file},WebUI 地址 ${this.config.gateway.host || "0.0.0.0"}:${this.config.gateway.port}`);
498
+ }
499
+ return this.config;
500
+ }
501
+ save() {
502
+ const config = this.load();
503
+ mkdirSync(this.dataDir, { recursive: true });
504
+ const temp = `${this.file}.${process.pid}.tmp`;
505
+ writeFileSync(temp, JSON.stringify(config, null, 2) + "\n");
506
+ try {
507
+ renameSync(temp, this.file);
508
+ } catch (error) {
509
+ rmSync(temp, { force: true });
510
+ throw error;
511
+ }
512
+ }
513
+ /** The default instance name if at least one instance exists, else undefined */
514
+ defaultInstance() {
515
+ const config = this.load();
516
+ const disk = this.diskInstances();
517
+ if (config.defaultInstance && disk.includes(config.defaultInstance)) return config.defaultInstance;
518
+ return disk[0];
519
+ }
520
+ /** Every instance directory on disk: the default instance first, then the rest in name order */
521
+ list() {
522
+ const config = this.load();
523
+ const names = this.diskInstances();
524
+ const primary = config.defaultInstance;
525
+ if (primary && names.includes(primary)) return [primary, ...names.filter((name) => name !== primary)];
526
+ return names;
527
+ }
528
+ exists(name) {
529
+ if (!isValidInstanceName(name)) return false;
530
+ this.load();
531
+ return existsSync(path.join(this.instancesDir, name));
532
+ }
533
+ settings(name) {
534
+ return this.load().instances[name] ?? { autostart: false };
535
+ }
536
+ /** The instances to start with the manager */
537
+ autostart() {
538
+ const known = new Set(this.list());
539
+ return Object.entries(this.load().instances).filter(([name, settings]) => settings.autostart && known.has(name)).map(([name]) => name);
540
+ }
541
+ setAutostart(name, autostart) {
542
+ const config = this.load();
543
+ config.instances[name] = {
544
+ ...config.instances[name],
545
+ autostart
546
+ };
547
+ this.save();
548
+ }
549
+ create(name, options = {}) {
550
+ if (!isValidInstanceName(name)) throw new RegistryError(400, INVALID_INSTANCE_NAME);
551
+ if (this.exists(name)) throw new RegistryError(409, `实例 ${name} 已存在`);
552
+ mkdirSync(path.join(this.instancesDir, name), { recursive: true });
553
+ const config = this.load();
554
+ config.instances[name] = { autostart: options.autostart === true };
555
+ if (!config.defaultInstance || !existsSync(path.join(this.instancesDir, config.defaultInstance))) config.defaultInstance = name;
556
+ this.save();
557
+ }
558
+ rename(from, to) {
559
+ if (!isValidInstanceName(from) || !isValidInstanceName(to)) throw new RegistryError(400, INVALID_INSTANCE_NAME);
560
+ if (!this.exists(from)) throw new RegistryError(404, `没有实例 ${from}`);
561
+ if (from === to) return;
562
+ if (this.exists(to)) throw new RegistryError(409, `实例 ${to} 已存在`);
563
+ renameSync(path.join(this.instancesDir, from), path.join(this.instancesDir, to));
564
+ this.cleanStateFiles(from);
565
+ const config = this.load();
566
+ let dirty = false;
567
+ const current = config.instances[from];
568
+ if (current) {
569
+ config.instances[to] = current;
570
+ delete config.instances[from];
571
+ dirty = true;
572
+ }
573
+ if (config.defaultInstance === from) {
574
+ config.defaultInstance = to;
575
+ dirty = true;
576
+ }
577
+ if (dirty) this.save();
578
+ }
579
+ remove(name) {
580
+ if (!isValidInstanceName(name)) throw new RegistryError(400, INVALID_INSTANCE_NAME);
581
+ if (!this.exists(name)) throw new RegistryError(404, `没有实例 ${name}`);
582
+ rmSync(path.join(this.instancesDir, name), {
583
+ recursive: true,
584
+ force: true
585
+ });
586
+ this.cleanStateFiles(name);
587
+ const config = this.load();
588
+ let dirty = false;
589
+ if (name in config.instances) {
590
+ delete config.instances[name];
591
+ dirty = true;
592
+ }
593
+ if (config.defaultInstance === name) {
594
+ config.defaultInstance = this.diskInstances()[0] ?? null;
595
+ dirty = true;
596
+ }
597
+ if (dirty) this.save();
598
+ }
599
+ setGateway(patch) {
600
+ const config = this.load();
601
+ if (patch.host !== void 0) {
602
+ if (typeof patch.host !== "string") throw new RegistryError(400, "监听地址格式不正确");
603
+ config.gateway.host = patch.host.trim();
604
+ }
605
+ if (patch.port !== void 0) {
606
+ if (!isPort(patch.port)) throw new RegistryError(400, "端口必须是 1 到 65535 之间的整数");
607
+ config.gateway.port = patch.port;
608
+ }
609
+ this.save();
610
+ return { ...config.gateway };
611
+ }
612
+ diskInstances() {
613
+ try {
614
+ return readdirSync(this.instancesDir, { withFileTypes: true }).filter((entry) => entry.isDirectory() && isValidInstanceName(entry.name)).map((entry) => entry.name).sort((a, b) => a.localeCompare(b));
615
+ } catch {
616
+ return [];
617
+ }
618
+ }
619
+ cleanStateFiles(name) {
620
+ const stateDir = path.join(this.dataDir, "state", "instances");
621
+ rmSync(path.join(stateDir, `${name}.json`), { force: true });
622
+ rmSync(path.join(stateDir, `${name}.sock`), { force: true });
623
+ }
624
+ /** The address the default instance's WebUI had before the manager, if it had its own settings for it */
625
+ legacyGateway() {
626
+ try {
627
+ const webui = JSON.parse(readFileSync(path.join(this.instancesDir, DEFAULT_INSTANCE, "settings.json"), "utf8"))?.webui;
628
+ if (!webui || typeof webui !== "object") return;
629
+ return {
630
+ ...typeof webui.host === "string" ? { host: webui.host } : {},
631
+ ...isPort(webui.port) ? { port: webui.port } : {}
632
+ };
633
+ } catch {
634
+ return;
635
+ }
636
+ }
637
+ };
638
+ var RegistryError = class extends Error {
639
+ status;
640
+ constructor(status, message) {
641
+ super(message);
642
+ this.status = status;
643
+ }
644
+ };
645
+ function isPort(value) {
646
+ return Number.isInteger(value) && value > 0 && value <= 65535;
647
+ }
648
+ function normalize(saved, disk, legacy) {
649
+ const gateway = saved?.gateway && typeof saved.gateway === "object" ? saved.gateway : legacy ?? {};
650
+ const instances = {};
651
+ if (saved?.instances && typeof saved.instances === "object") for (const [name, settings] of Object.entries(saved.instances)) {
652
+ if (!isValidInstanceName(name) || !settings || typeof settings !== "object") continue;
653
+ instances[name] = { autostart: settings.autostart === true };
654
+ }
655
+ else {
656
+ const initial = disk.includes("default") ? DEFAULT_INSTANCE : disk[0];
657
+ if (initial) instances[initial] = { autostart: true };
658
+ }
659
+ let defaultInstance;
660
+ if (saved && "defaultInstance" in saved) defaultInstance = typeof saved.defaultInstance === "string" && isValidInstanceName(saved.defaultInstance) ? saved.defaultInstance : null;
661
+ else defaultInstance = disk.includes("default") ? DEFAULT_INSTANCE : disk[0] ?? ("default" in instances ? "default" : null);
662
+ return {
663
+ gateway: {
664
+ host: typeof gateway.host === "string" ? gateway.host : DEFAULT_GATEWAY_HOST,
665
+ port: isPort(gateway.port) ? gateway.port : DEFAULT_GATEWAY_PORT
666
+ },
667
+ defaultInstance,
668
+ instances
669
+ };
670
+ }
671
+ //#endregion
672
+ //#region src/main/manager/api.ts
673
+ var INSTANCE_ACTION = /^\/api\/manager\/instances\/([^/]+)\/(start|stop|restart)$/;
674
+ var INSTANCE_LOGS = /^\/api\/manager\/instances\/([^/]+)\/logs$/;
675
+ var INSTANCE_ITEM = /^\/api\/manager\/instances\/([^/]+)$/;
676
+ function isActive(phase) {
677
+ return phase === "starting" || phase === "running" || phase === "stopping";
678
+ }
679
+ function decodeSegment(raw) {
680
+ try {
681
+ return decodeURIComponent(raw);
682
+ } catch {
683
+ return;
684
+ }
685
+ }
686
+ async function readJson(request, response) {
687
+ let raw;
688
+ try {
689
+ raw = await readBody(request);
690
+ } catch (error) {
691
+ json(response, 413, {
692
+ success: false,
693
+ message: error.message
694
+ });
695
+ return;
696
+ }
697
+ if (!raw.trim()) return {};
698
+ try {
699
+ const parsed = JSON.parse(raw);
700
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
701
+ json(response, 400, {
702
+ success: false,
703
+ message: "请求格式不对"
704
+ });
705
+ return;
706
+ }
707
+ return parsed;
708
+ } catch {
709
+ json(response, 400, {
710
+ success: false,
711
+ message: "请求格式不对"
712
+ });
713
+ return;
714
+ }
715
+ }
716
+ function respondError(response, error) {
717
+ if (error instanceof RegistryError) {
718
+ json(response, error.status, {
719
+ success: false,
720
+ message: error.message
721
+ });
722
+ return;
723
+ }
724
+ json(response, 500, {
725
+ success: false,
726
+ message: error instanceof Error ? error.message : String(error)
727
+ });
728
+ }
729
+ function createManagerApi(options) {
730
+ const { registry } = options;
731
+ const infoOf = (name) => ({
732
+ ...options.statusOf(name),
733
+ autostart: registry.settings(name).autostart,
734
+ isDefault: name === registry.defaultInstance()
735
+ });
736
+ return async (request, response, route) => {
737
+ const method = request.method ?? "GET";
738
+ if (route === "/api/manager/instances" && method === "GET") {
739
+ json(response, 200, {
740
+ success: true,
741
+ data: {
742
+ selected: options.selected(),
743
+ instances: registry.list().map(infoOf)
744
+ }
745
+ });
746
+ return true;
747
+ }
748
+ if (route === "/api/manager/instances" && method === "POST") {
749
+ const body = await readJson(request, response);
750
+ if (!body) return true;
751
+ const name = typeof body.name === "string" ? body.name.trim() : "";
752
+ if (!name) {
753
+ json(response, 400, {
754
+ success: false,
755
+ message: "实例名不能为空"
756
+ });
757
+ return true;
758
+ }
759
+ try {
760
+ registry.create(name, { autostart: body.autostart === true });
761
+ } catch (error) {
762
+ respondError(response, error);
763
+ return true;
764
+ }
765
+ if (body.start === true) options.instance(name).start();
766
+ json(response, 200, {
767
+ success: true,
768
+ data: infoOf(name)
769
+ });
770
+ return true;
771
+ }
772
+ const actionMatch = INSTANCE_ACTION.exec(route);
773
+ if (actionMatch && method === "POST") {
774
+ const name = decodeSegment(actionMatch[1]);
775
+ if (!name || !registry.exists(name)) {
776
+ json(response, 404, {
777
+ success: false,
778
+ message: `没有实例 ${name ?? actionMatch[1]}`
779
+ });
780
+ return true;
781
+ }
782
+ const child = options.instance(name);
783
+ if (actionMatch[2] === "start") child.start();
784
+ else if (actionMatch[2] === "stop") await child.stop();
785
+ else await child.restart();
786
+ json(response, 200, {
787
+ success: true,
788
+ data: infoOf(name)
789
+ });
790
+ return true;
791
+ }
792
+ const logsMatch = INSTANCE_LOGS.exec(route);
793
+ if (logsMatch && method === "GET") {
794
+ const name = decodeSegment(logsMatch[1]);
795
+ if (!name || !registry.exists(name)) {
796
+ json(response, 404, {
797
+ success: false,
798
+ message: `没有实例 ${name ?? logsMatch[1]}`
799
+ });
800
+ return true;
801
+ }
802
+ json(response, 200, {
803
+ success: true,
804
+ data: {
805
+ name,
806
+ lines: options.recentOutput(name)
807
+ }
808
+ });
809
+ return true;
810
+ }
811
+ const itemMatch = INSTANCE_ITEM.exec(route);
812
+ if (itemMatch && (method === "PATCH" || method === "DELETE")) {
813
+ const name = decodeSegment(itemMatch[1]);
814
+ if (!name || !registry.exists(name)) {
815
+ json(response, 404, {
816
+ success: false,
817
+ message: `没有实例 ${name ?? itemMatch[1]}`
818
+ });
819
+ return true;
820
+ }
821
+ if (method === "DELETE") {
822
+ if (await options.isLockedExternal?.(name)) {
823
+ json(response, 409, {
824
+ success: false,
825
+ message: "实例正在其他进程中运行,请先停止后再删除"
826
+ });
827
+ return true;
828
+ }
829
+ if (isActive(options.statusOf(name).phase)) await options.instance(name).stop();
830
+ try {
831
+ registry.remove(name);
832
+ options.onRemoved?.(name);
833
+ } catch (error) {
834
+ respondError(response, error);
835
+ return true;
836
+ }
837
+ json(response, 200, { success: true });
838
+ return true;
839
+ }
840
+ const body = await readJson(request, response);
841
+ if (!body) return true;
842
+ let currentName = name;
843
+ if (body.renameTo !== void 0) {
844
+ if (typeof body.renameTo !== "string") {
845
+ json(response, 400, {
846
+ success: false,
847
+ message: "新实例名格式不对"
848
+ });
849
+ return true;
850
+ }
851
+ const nextName = body.renameTo.trim();
852
+ if (!isValidInstanceName(nextName)) {
853
+ json(response, 400, {
854
+ success: false,
855
+ message: INVALID_INSTANCE_NAME
856
+ });
857
+ return true;
858
+ }
859
+ if (nextName !== name) {
860
+ if (registry.exists(nextName)) {
861
+ json(response, 409, {
862
+ success: false,
863
+ message: `实例 ${nextName} 已存在`
864
+ });
865
+ return true;
866
+ }
867
+ if (await options.isLockedExternal?.(name)) {
868
+ json(response, 409, {
869
+ success: false,
870
+ message: "实例正在其他进程中运行,请先停止后再重命名"
871
+ });
872
+ return true;
873
+ }
874
+ const phase = options.statusOf(name).phase;
875
+ const wasActive = isActive(phase);
876
+ const shouldRestart = phase === "running" || phase === "starting";
877
+ if (wasActive) await options.instance(name).stop();
878
+ try {
879
+ registry.rename(name, nextName);
880
+ options.onRenamed?.(name, nextName);
881
+ } catch (error) {
882
+ if (shouldRestart) options.instance(name).start();
883
+ respondError(response, error);
884
+ return true;
885
+ }
886
+ currentName = nextName;
887
+ if (shouldRestart) options.instance(currentName).start();
888
+ }
889
+ }
890
+ if (body.autostart !== void 0) {
891
+ if (typeof body.autostart !== "boolean") {
892
+ json(response, 400, {
893
+ success: false,
894
+ message: "autostart 必须是布尔值"
895
+ });
896
+ return true;
897
+ }
898
+ registry.setAutostart(currentName, body.autostart);
899
+ }
900
+ json(response, 200, {
901
+ success: true,
902
+ data: infoOf(currentName)
903
+ });
904
+ return true;
905
+ }
906
+ if (route === "/api/manager/gateway" && method === "GET") {
907
+ json(response, 200, {
908
+ success: true,
909
+ data: options.gatewayState()
910
+ });
911
+ return true;
912
+ }
913
+ if (route === "/api/manager/gateway" && (method === "PATCH" || method === "POST")) {
914
+ const body = await readJson(request, response);
915
+ if (!body) return true;
916
+ const before = options.gatewayState();
917
+ const locked = new Set(before.envLocked.map((item) => item.path));
918
+ const patch = {};
919
+ if (body.host !== void 0 && !locked.has("webui.host")) {
920
+ if (typeof body.host !== "string") {
921
+ json(response, 400, {
922
+ success: false,
923
+ message: "监听地址格式不正确"
924
+ });
925
+ return true;
926
+ }
927
+ patch.host = body.host.trim();
928
+ }
929
+ if (body.port !== void 0 && !locked.has("webui.port")) {
930
+ if (typeof body.port !== "number" || !Number.isInteger(body.port) || body.port < 1 || body.port > 65535) {
931
+ json(response, 400, {
932
+ success: false,
933
+ message: "端口必须是 1 到 65535 之间的整数"
934
+ });
935
+ return true;
936
+ }
937
+ patch.port = body.port;
938
+ }
939
+ try {
940
+ if (patch.host !== void 0 || patch.port !== void 0) registry.setGateway(patch);
941
+ } catch (error) {
942
+ respondError(response, error);
943
+ return true;
944
+ }
945
+ const after = options.gatewayState();
946
+ const changed = after.host !== before.host || after.port !== before.port;
947
+ json(response, 200, {
948
+ success: true,
949
+ data: {
950
+ ...after,
951
+ restarted: changed
952
+ }
953
+ });
954
+ if (changed) setTimeout(() => options.onGatewayChanged?.(after.host, after.port), 150);
955
+ return true;
956
+ }
957
+ if (route === "/api/manager/network-interfaces" && method === "GET") {
958
+ const isDocker = isDockerEnvironment();
959
+ const addresses = [];
960
+ if (!isDocker) {
961
+ const interfaces = networkInterfaces();
962
+ for (const name of Object.keys(interfaces)) for (const iface of interfaces[name] ?? []) if (iface.family === "IPv4" && !iface.internal) addresses.push(iface.address);
963
+ }
964
+ json(response, 200, {
965
+ success: true,
966
+ data: addresses,
967
+ isDocker
968
+ });
969
+ return true;
970
+ }
971
+ return false;
972
+ };
973
+ }
974
+ //#endregion
975
+ //#region src/main/manager/args.ts
976
+ /**
977
+ * How the arguments llbot.js was given are split between the manager and the instances it runs. The launchers
978
+ * (desktop app, CLI, Docker) keep passing what they passed when each process was one instance.
979
+ *
980
+ * Only the bot's own arguments are known here. Anything else belongs to the plugins (a protocol plugin's login
981
+ * mode, `--plugin` to install one) and goes to the instance the launch names, as it did when that was the only one.
982
+ */
983
+ /** The manager's own: the WebUI port is the gateway's, the parent is the manager's */
984
+ var MANAGER_VALUE = /* @__PURE__ */ new Set([
985
+ "--webui-port",
986
+ "--parent-pid",
987
+ "--instance"
988
+ ]);
989
+ /** The bot's own settings for every instance; `--plugin-dir` takes a value */
990
+ var SHARED_VALUE = /* @__PURE__ */ new Set(["--plugin-dir"]);
991
+ var SHARED_FLAG = /* @__PURE__ */ new Set([
992
+ "--plugin-hmr",
993
+ "--dev",
994
+ "--debug"
995
+ ]);
996
+ var nameOf = (arg) => arg.startsWith("-") && arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg;
997
+ /** Whether `arg` at `index` is followed by its value as a separate argument */
998
+ var takesNext = (argv, index) => argv[index + 1] !== void 0 && !argv[index + 1].startsWith("-");
999
+ function splitArgs(argv) {
1000
+ const result = {
1001
+ target: [],
1002
+ shared: []
1003
+ };
1004
+ for (let i = 0; i < argv.length; i++) {
1005
+ const arg = argv[i];
1006
+ if (arg === "--") continue;
1007
+ const name = nameOf(arg);
1008
+ const inline = arg !== name;
1009
+ if (MANAGER_VALUE.has(name)) {
1010
+ const value = inline ? arg.slice(name.length + 1) : takesNext(argv, i) ? argv[++i] : void 0;
1011
+ if (name === "--webui-port" && value !== void 0 && /^\d+$/.test(value) && +value > 0 && +value <= 65535) result.webuiPort = +value;
1012
+ continue;
1013
+ }
1014
+ if (SHARED_FLAG.has(name)) {
1015
+ result.shared.push(arg);
1016
+ continue;
1017
+ }
1018
+ if (SHARED_VALUE.has(name)) {
1019
+ result.shared.push(arg);
1020
+ if (!inline && takesNext(argv, i)) result.shared.push(argv[++i]);
1021
+ continue;
1022
+ }
1023
+ result.target.push(arg);
1024
+ if (!inline && takesNext(argv, i)) result.target.push(argv[++i]);
1025
+ }
1026
+ return result;
1027
+ }
1028
+ //#endregion
1029
+ //#region src/main/manager/auth.ts
1030
+ var hashPassword = (password) => createHash("sha256").update(password).digest("hex");
1031
+ var FAILURES_BEFORE_LOCK = 4;
1032
+ var LOCK_TIME = 36e5;
1033
+ /**
1034
+ * The WebUI login of all instances, checked once in the gateway. Same protocol as an instance's own login had
1035
+ * (BE/auth.ts): the browser presents sha256(password); refusals carry X-Webui-Auth; four wrong passwords in a row
1036
+ * lock it for an hour, whatever the address.
1037
+ */
1038
+ var GatewayAuth = class {
1039
+ options;
1040
+ token = "";
1041
+ mtimeMs = -1;
1042
+ failures = 0;
1043
+ lockedUntil = 0;
1044
+ constructor(options) {
1045
+ this.options = options;
1046
+ }
1047
+ /** The password; re-read when the file changed (the desktop app or a hand edit may reset it) */
1048
+ getToken() {
1049
+ let mtimeMs;
1050
+ try {
1051
+ mtimeMs = statSync(this.options.file).mtimeMs;
1052
+ } catch {
1053
+ return this.token;
1054
+ }
1055
+ if (mtimeMs !== this.mtimeMs) {
1056
+ this.token = readFileSync(this.options.file, "utf8").trim();
1057
+ this.mtimeMs = mtimeMs;
1058
+ }
1059
+ return this.token;
1060
+ }
1061
+ setToken(token) {
1062
+ mkdirSync(path.dirname(this.options.file), { recursive: true });
1063
+ writeFileSync(this.options.file, token.trim(), "utf8");
1064
+ this.token = token.trim();
1065
+ this.mtimeMs = statSync(this.options.file).mtimeMs;
1066
+ }
1067
+ /** Whether `presented` is the password, without counting a wrong one: for requests that only pass it along */
1068
+ matches(presented) {
1069
+ const token = this.getToken();
1070
+ return !!token && !!presented && safeEqual(presented, hashPassword(token));
1071
+ }
1072
+ /** Checks a request's password, a wrong one counting towards the lock; undefined when it may pass */
1073
+ check(presented, ip, method, url) {
1074
+ const token = this.getToken();
1075
+ if (!token) {
1076
+ this.access(ip, method, url, 401, "未设置密码");
1077
+ return {
1078
+ status: 401,
1079
+ reason: "unset",
1080
+ body: {
1081
+ success: false,
1082
+ message: "请先设置WebUI密码"
1083
+ }
1084
+ };
1085
+ }
1086
+ const now = this.options.now?.() ?? Date.now();
1087
+ if (this.lockedUntil) {
1088
+ if (now < this.lockedUntil) {
1089
+ const remainingMinutes = Math.ceil((this.lockedUntil - now) / 6e4);
1090
+ this.access(ip, method, url, 403, `账户锁定中,剩余${remainingMinutes}分钟`);
1091
+ return {
1092
+ status: 403,
1093
+ reason: "locked",
1094
+ body: {
1095
+ success: false,
1096
+ message: `密码错误次数过多,请在 ${remainingMinutes} 分钟后重试`,
1097
+ locked: true,
1098
+ remainingMinutes
1099
+ }
1100
+ };
1101
+ }
1102
+ this.failures = 0;
1103
+ this.lockedUntil = 0;
1104
+ }
1105
+ if (!presented) return {
1106
+ status: 403,
1107
+ reason: "required",
1108
+ body: {
1109
+ success: false,
1110
+ message: "请输入密码"
1111
+ }
1112
+ };
1113
+ if (!safeEqual(presented, hashPassword(token))) {
1114
+ this.failures++;
1115
+ if (this.failures >= FAILURES_BEFORE_LOCK) {
1116
+ this.lockedUntil = now + LOCK_TIME;
1117
+ this.access(ip, method, url, 403, `密码连续错误${FAILURES_BEFORE_LOCK}次,账户锁定1小时`);
1118
+ return {
1119
+ status: 403,
1120
+ reason: "locked",
1121
+ body: {
1122
+ success: false,
1123
+ message: `密码连续错误${FAILURES_BEFORE_LOCK}次,账户已被锁定1小时`,
1124
+ locked: true,
1125
+ remainingMinutes: 60
1126
+ }
1127
+ };
1128
+ }
1129
+ const remainingAttempts = FAILURES_BEFORE_LOCK - this.failures;
1130
+ this.access(ip, method, url, 403, `Token验证失败,剩余${remainingAttempts}次尝试`);
1131
+ return {
1132
+ status: 403,
1133
+ reason: "wrong",
1134
+ body: {
1135
+ success: false,
1136
+ message: `Token校验失败,剩余尝试次数:${remainingAttempts}`,
1137
+ remainingAttempts
1138
+ }
1139
+ };
1140
+ }
1141
+ if (this.failures > 0) {
1142
+ this.access(ip, method, url, 200, "登录成功,重置失败计数");
1143
+ this.failures = 0;
1144
+ this.lockedUntil = 0;
1145
+ }
1146
+ this.access(ip, method, url, 200);
1147
+ }
1148
+ access(ip, method, url, status, message) {
1149
+ if (!this.options.accessLog) return;
1150
+ try {
1151
+ appendFileSync(this.options.accessLog, `${(/* @__PURE__ */ new Date()).toISOString()} | IP: ${ip} | ${method} ${url} | Status: ${status}${message ? ` | ${message}` : ""}\n`);
1152
+ } catch (error) {
1153
+ this.options.log?.warn(`写入访问日志失败:${error.message}`);
1154
+ }
1155
+ }
1156
+ };
1157
+ function safeEqual(a, b) {
1158
+ const left = Buffer.from(a);
1159
+ const right = Buffer.from(b);
1160
+ return left.length === right.length && timingSafeEqual(left, right);
1161
+ }
1162
+ //#endregion
1163
+ //#region src/main/manager/coreUpdateHandler.ts
1164
+ var RESUME_FILE = "resume-instances.json";
1165
+ /** Reads custom npm registries configured on `builtin:market` in the selected or default instance, if any */
1166
+ function managerRegistries(instancesDir, preferred) {
1167
+ for (const name of [...new Set(preferred)]) {
1168
+ const file = path.join(instancesDir, name, "plugins.json");
1169
+ if (!existsSync(file)) continue;
1170
+ try {
1171
+ const entry = JSON.parse(readFileSync(file, "utf8"))?.entries?.find((item) => item?.id === "builtin:market" || item?.name === "builtin:market");
1172
+ if (entry?.config) {
1173
+ const settings = new MarketSchema(entry.config);
1174
+ return new Registries(registriesOf(settings));
1175
+ }
1176
+ } catch {}
1177
+ }
1178
+ return new Registries(registriesOf(new MarketSchema(void 0)));
1179
+ }
1180
+ /** Saves the instances running before a core-update restart so the new manager brings them right back */
1181
+ function saveResumeInstances(stateDir, names) {
1182
+ const valid = [...new Set(names)].filter(isValidInstanceName);
1183
+ if (!valid.length) return;
1184
+ try {
1185
+ mkdirSync(stateDir, { recursive: true });
1186
+ writeFileSync(path.join(stateDir, RESUME_FILE), JSON.stringify(valid));
1187
+ } catch {}
1188
+ }
1189
+ /** Reads and deletes the one-shot resume list written before a core-update restart */
1190
+ function consumeResumeInstances(stateDir) {
1191
+ const file = path.join(stateDir, RESUME_FILE);
1192
+ if (!existsSync(file)) return [];
1193
+ try {
1194
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
1195
+ return Array.isArray(parsed) ? parsed.filter((v) => typeof v === "string" && isValidInstanceName(v)) : [];
1196
+ } catch {
1197
+ return [];
1198
+ } finally {
1199
+ rmSync(file, { force: true });
1200
+ }
1201
+ }
1202
+ /** Serves `/api/core-update/*` directly from the manager gateway with the same contract as coreUpdate.ts */
1203
+ function createCoreUpdateHandler(updater) {
1204
+ const respond = async (response, task) => {
1205
+ try {
1206
+ json(response, 200, {
1207
+ success: true,
1208
+ data: await task()
1209
+ });
1210
+ } catch (error) {
1211
+ json(response, error instanceof CoreUpdateError ? error.status : 500, {
1212
+ success: false,
1213
+ message: error instanceof Error ? error.message : String(error)
1214
+ });
1215
+ }
1216
+ };
1217
+ return async (request, response, route, query) => {
1218
+ const method = request.method ?? "GET";
1219
+ if (route === "/api/core-update/status" && method === "GET") {
1220
+ await respond(response, async () => updater.status());
1221
+ return true;
1222
+ }
1223
+ if (route === "/api/core-update/check" && method === "POST") {
1224
+ await respond(response, () => updater.check());
1225
+ return true;
1226
+ }
1227
+ if (route === "/api/core-update/update" && method === "POST") {
1228
+ let version = "";
1229
+ try {
1230
+ const raw = await readBody(request);
1231
+ if (raw.trim()) {
1232
+ const body = JSON.parse(raw);
1233
+ version = String(body?.version ?? "");
1234
+ }
1235
+ } catch {
1236
+ json(response, 400, {
1237
+ success: false,
1238
+ message: "请求格式不对"
1239
+ });
1240
+ return true;
1241
+ }
1242
+ await respond(response, () => updater.update(version));
1243
+ return true;
1244
+ }
1245
+ if (route === "/api/core-update/release-notes" && method === "GET") {
1246
+ const version = query.get("version") ?? updater.status().latest ?? "";
1247
+ await respond(response, () => updater.releaseNotes(version));
1248
+ return true;
1249
+ }
1250
+ return false;
1251
+ };
1252
+ }
1253
+ //#endregion
1254
+ //#region src/main/manager/instance.ts
1255
+ var RESTART_WINDOW = 6e4;
1256
+ var MAX_BACKOFF = 3e4;
1257
+ var LOG_LINES = 300;
1258
+ /**
1259
+ * One instance: llbot-core.js forked with an IPC channel. Started again when it asks for a restart (after an update
1260
+ * of its plugins) or crashes, with backoff; marked failed when it keeps crashing.
1261
+ */
1262
+ var InstanceProcess = class {
1263
+ name;
1264
+ options;
1265
+ child;
1266
+ phase = "stopped";
1267
+ webuiPort;
1268
+ exitCode;
1269
+ error;
1270
+ startedAt;
1271
+ crashes = [];
1272
+ retry;
1273
+ exited;
1274
+ lines = [];
1275
+ constructor(name, options) {
1276
+ this.name = name;
1277
+ this.options = options;
1278
+ }
1279
+ status() {
1280
+ return {
1281
+ name: this.name,
1282
+ phase: this.phase,
1283
+ ...this.child?.pid ? { pid: this.child.pid } : {},
1284
+ ...this.webuiPort ? { webuiPort: this.webuiPort } : {},
1285
+ ...this.exitCode !== void 0 ? { exitCode: this.exitCode } : {},
1286
+ ...this.error ? { error: this.error } : {},
1287
+ ...this.startedAt ? { startedAt: this.startedAt } : {}
1288
+ };
1289
+ }
1290
+ /** The last lines of its output, for the WebUI when it failed to start */
1291
+ recentOutput() {
1292
+ return [...this.lines];
1293
+ }
1294
+ get running() {
1295
+ return this.phase === "starting" || this.phase === "running";
1296
+ }
1297
+ start() {
1298
+ if (this.child || this.phase === "stopping") return;
1299
+ clearTimeout(this.retry);
1300
+ this.retry = void 0;
1301
+ this.error = void 0;
1302
+ this.crashes = this.phase === "failed" ? [] : this.crashes;
1303
+ this.spawn();
1304
+ }
1305
+ /** Asks it to shut down cleanly; kills it when it has not exited after the stop timeout */
1306
+ async stop(timeout = this.options.stopTimeout ?? 25e3) {
1307
+ clearTimeout(this.retry);
1308
+ this.retry = void 0;
1309
+ const child = this.child;
1310
+ if (!child) {
1311
+ if (this.phase !== "stopped") this.set("stopped");
1312
+ return;
1313
+ }
1314
+ if (this.phase !== "stopping") {
1315
+ this.set("stopping");
1316
+ this.send({ type: "shutdown" });
1317
+ }
1318
+ const timer = setTimeout(() => {
1319
+ this.options.log?.(`实例 ${this.name} 在 ${Math.round(timeout / 1e3)} 秒内没有退出,强制结束`);
1320
+ child.kill("SIGKILL");
1321
+ }, timeout);
1322
+ try {
1323
+ await this.exited;
1324
+ } finally {
1325
+ clearTimeout(timer);
1326
+ }
1327
+ }
1328
+ async restart() {
1329
+ await this.stop();
1330
+ this.start();
1331
+ }
1332
+ /** Sends an IPC message to the running child; returns false if no connected child exists */
1333
+ sendMessage(message) {
1334
+ const child = this.child;
1335
+ if (!child?.connected) return false;
1336
+ child.send(message, () => {});
1337
+ return true;
1338
+ }
1339
+ spawn() {
1340
+ this.webuiPort = void 0;
1341
+ this.exitCode = void 0;
1342
+ this.startedAt = Date.now();
1343
+ const env = {
1344
+ ...this.options.env ?? process.env,
1345
+ [MANAGED_ENV]: "1",
1346
+ [SUPERVISED_ENV]: "1",
1347
+ [GATEWAY_SECRET_ENV]: this.options.secret,
1348
+ LLBOT_WEBUI_HOST: "127.0.0.1",
1349
+ LLBOT_WEBUI_PORT: "0"
1350
+ };
1351
+ delete env.LLBOT_INSTANCE;
1352
+ if (env.FORCE_COLOR === void 0 && process.stdout.isTTY) env.FORCE_COLOR = "1";
1353
+ const child = fork(this.options.core, [
1354
+ ...this.options.args(),
1355
+ "--instance",
1356
+ this.name,
1357
+ `--parent-pid=${process.pid}`
1358
+ ], {
1359
+ execArgv: [...this.options.execArgv ?? process.execArgv],
1360
+ env,
1361
+ stdio: [
1362
+ "ignore",
1363
+ "pipe",
1364
+ "pipe",
1365
+ "ipc"
1366
+ ]
1367
+ });
1368
+ this.child = child;
1369
+ this.set("starting");
1370
+ this.pipe(child.stdout, "stdout");
1371
+ this.pipe(child.stderr, "stderr");
1372
+ child.on("message", (message) => {
1373
+ if (!isInstanceMessage(message) || child !== this.child) return;
1374
+ if (message.type === "webui") {
1375
+ this.webuiPort = message.port;
1376
+ if (this.phase === "starting") this.set("running");
1377
+ else this.options.onChange?.(this.status());
1378
+ } else this.options.onMessage?.(this.name, message);
1379
+ });
1380
+ let resolveExit;
1381
+ this.exited = new Promise((resolve) => {
1382
+ resolveExit = resolve;
1383
+ });
1384
+ child.once("error", (error) => {
1385
+ this.options.log?.(`无法启动实例 ${this.name}:${error.message}`);
1386
+ });
1387
+ child.once("exit", (code, signal) => {
1388
+ this.child = void 0;
1389
+ this.webuiPort = void 0;
1390
+ this.exitCode = code;
1391
+ this.options.onExit?.(this.name);
1392
+ resolveExit();
1393
+ this.exitedWith(code, signal);
1394
+ });
1395
+ }
1396
+ exitedWith(code, signal) {
1397
+ if (this.phase === "stopping") {
1398
+ this.set("stopped");
1399
+ return;
1400
+ }
1401
+ if (code === 75) {
1402
+ if (this.countCrash()) this.spawn();
1403
+ return;
1404
+ }
1405
+ if (code === 0) {
1406
+ this.set("stopped");
1407
+ return;
1408
+ }
1409
+ if (!this.countCrash()) return;
1410
+ const attempt = this.crashes.length;
1411
+ const delay = Math.min(1e3 * 2 ** (attempt - 1), MAX_BACKOFF);
1412
+ this.options.log?.(`实例 ${this.name} 意外退出(${code ?? signal}),${Math.round(delay / 1e3)} 秒后重启`);
1413
+ this.set("starting");
1414
+ this.retry = setTimeout(() => {
1415
+ this.retry = void 0;
1416
+ if (this.phase === "starting" && !this.child) this.spawn();
1417
+ }, delay);
1418
+ }
1419
+ /** Counts a restart; false, marking it failed, when there were too many within a minute */
1420
+ countCrash() {
1421
+ const now = Date.now();
1422
+ this.crashes = this.crashes.filter((time) => now - time < RESTART_WINDOW);
1423
+ this.crashes.push(now);
1424
+ if (this.crashes.length > (this.options.maxRestarts ?? 5)) {
1425
+ this.error = `一分钟内退出了 ${this.crashes.length} 次,已停止自动重启`;
1426
+ this.options.log?.(`实例 ${this.name} ${this.error}`);
1427
+ this.set("failed");
1428
+ return false;
1429
+ }
1430
+ return true;
1431
+ }
1432
+ send(message) {
1433
+ const child = this.child;
1434
+ if (!child?.connected) {
1435
+ child?.kill("SIGTERM");
1436
+ return;
1437
+ }
1438
+ child.send(message, (error) => {
1439
+ if (error) child.kill("SIGTERM");
1440
+ });
1441
+ }
1442
+ set(phase) {
1443
+ this.phase = phase;
1444
+ this.options.onChange?.(this.status());
1445
+ }
1446
+ pipe(stream, kind) {
1447
+ if (!stream) return;
1448
+ let rest = "";
1449
+ const emit = (line) => {
1450
+ this.lines.push(line);
1451
+ if (this.lines.length > LOG_LINES) this.lines.splice(0, this.lines.length - LOG_LINES);
1452
+ this.options.output?.(this.name, line, kind);
1453
+ };
1454
+ stream.setEncoding?.("utf8");
1455
+ stream.on("data", (chunk) => {
1456
+ const parts = (rest + chunk).split("\n");
1457
+ rest = parts.pop() ?? "";
1458
+ for (const part of parts) emit(part.endsWith("\r") ? part.slice(0, -1) : part);
1459
+ });
1460
+ stream.on("end", () => {
1461
+ if (rest) emit(rest);
1462
+ rest = "";
1463
+ });
1464
+ }
1465
+ };
1466
+ //#endregion
1467
+ //#region src/main/manager/packageCoordinator.ts
1468
+ var DEFAULT_TIMEOUT = 3e4;
1469
+ /**
1470
+ * Coordinates shared plugin directory changes across all managed child instances directly over Node IPC,
1471
+ * replacing tmp peer files and loopback TCP discovery for managed processes.
1472
+ */
1473
+ var PackageCoordinator = class {
1474
+ options;
1475
+ peers = /* @__PURE__ */ new Map();
1476
+ pending = /* @__PURE__ */ new Map();
1477
+ timeoutMs;
1478
+ constructor(options) {
1479
+ this.options = options;
1480
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT;
1481
+ }
1482
+ onMessage(instance, message) {
1483
+ switch (message.type) {
1484
+ case "pkg:register":
1485
+ this.peers.set(instance, {
1486
+ instance,
1487
+ peerId: message.id,
1488
+ roots: new Set(message.roots)
1489
+ });
1490
+ return;
1491
+ case "pkg:unregister": {
1492
+ const current = this.peers.get(instance);
1493
+ if (current && current.peerId === message.id) {
1494
+ this.peers.delete(instance);
1495
+ this.failPendingFor(instance, `${instance} 已注销插件协调`);
1496
+ }
1497
+ return;
1498
+ }
1499
+ case "pkg:rpc-result": {
1500
+ const call = this.pending.get(message.reqId);
1501
+ if (!call) return;
1502
+ this.pending.delete(message.reqId);
1503
+ clearTimeout(call.timer);
1504
+ if (message.error !== void 0) call.reject(new Error(message.error));
1505
+ else call.resolve(message.value);
1506
+ return;
1507
+ }
1508
+ case "pkg:broadcast":
1509
+ this.broadcast(instance, message);
1510
+ return;
1511
+ }
1512
+ }
1513
+ /** Called when a managed child process exits or disconnects */
1514
+ onExit(instance) {
1515
+ this.peers.delete(instance);
1516
+ this.failPendingFor(instance, `${instance} 在插件协调期间断开连接`);
1517
+ }
1518
+ /** Snapshot of registered peer instances sharing a canonical root (for diagnostics/tests) */
1519
+ registeredFor(root) {
1520
+ return [...this.peers.values()].filter((peer) => peer.roots.has(root)).map((peer) => peer.instance);
1521
+ }
1522
+ async broadcast(sender, message) {
1523
+ const targets = [...this.peers.values()].filter((peer) => peer.instance !== sender && peer.peerId !== message.senderId && peer.roots.has(message.root));
1524
+ if (targets.length === 0) {
1525
+ this.options.send(sender, {
1526
+ type: "pkg:broadcast-result",
1527
+ reqId: message.reqId,
1528
+ results: []
1529
+ });
1530
+ return;
1531
+ }
1532
+ if (message.action === "prepare") {
1533
+ const failed = (await Promise.allSettled(targets.map((target) => this.call(target.instance, "prepare", message.change)))).find((result) => result.status === "rejected");
1534
+ if (failed) this.options.send(sender, {
1535
+ type: "pkg:broadcast-result",
1536
+ reqId: message.reqId,
1537
+ error: failed.reason instanceof Error ? failed.reason.message : String(failed.reason)
1538
+ });
1539
+ else this.options.send(sender, {
1540
+ type: "pkg:broadcast-result",
1541
+ reqId: message.reqId,
1542
+ results: []
1543
+ });
1544
+ return;
1545
+ }
1546
+ const results = await Promise.all(targets.map(async (target) => {
1547
+ try {
1548
+ return await this.call(target.instance, "finish", message.change, message.applied);
1549
+ } catch (error) {
1550
+ return {
1551
+ instance: target.instance,
1552
+ pid: this.options.pidOf?.(target.instance) ?? 0,
1553
+ status: "failed",
1554
+ reason: error instanceof Error ? error.message : String(error)
1555
+ };
1556
+ }
1557
+ }));
1558
+ this.options.send(sender, {
1559
+ type: "pkg:broadcast-result",
1560
+ reqId: message.reqId,
1561
+ results
1562
+ });
1563
+ }
1564
+ call(target, action, change, applied) {
1565
+ const reqId = randomUUID();
1566
+ return new Promise((resolve, reject) => {
1567
+ const timer = setTimeout(() => {
1568
+ this.pending.delete(reqId);
1569
+ reject(/* @__PURE__ */ new Error(`${target} 未响应插件协调请求`));
1570
+ }, this.timeoutMs);
1571
+ timer.unref?.();
1572
+ this.pending.set(reqId, {
1573
+ target,
1574
+ timer,
1575
+ resolve,
1576
+ reject
1577
+ });
1578
+ if (!this.options.send(target, {
1579
+ type: "pkg:rpc",
1580
+ reqId,
1581
+ action,
1582
+ change,
1583
+ applied
1584
+ })) {
1585
+ this.pending.delete(reqId);
1586
+ clearTimeout(timer);
1587
+ reject(/* @__PURE__ */ new Error(`${target} 在插件协调期间断开连接`));
1588
+ }
1589
+ });
1590
+ }
1591
+ failPendingFor(instance, reason) {
1592
+ for (const [reqId, call] of this.pending) {
1593
+ if (call.target !== instance) continue;
1594
+ this.pending.delete(reqId);
1595
+ clearTimeout(call.timer);
1596
+ call.reject(new Error(reason));
1597
+ }
1598
+ }
1599
+ };
1600
+ //#endregion
1601
+ //#region src/main/manager/index.ts
1602
+ /**
1603
+ * llbot-manager.js: runs every instance of this data directory as a child (llbot-core.js --instance <name>) and
1604
+ * serves their WebUIs on one address with one login. llbot.js, the supervisor every launcher runs, starts this and
1605
+ * starts it again when it asks for a restart.
1606
+ */
1607
+ var time = () => (/* @__PURE__ */ new Date()).toLocaleTimeString("zh-CN", { hour12: false });
1608
+ var log = {
1609
+ info: (message) => console.log(`${time()} [manager] ${message}`),
1610
+ warn: (message) => console.warn(`${time()} [manager] ${message}`),
1611
+ error: (message) => console.error(`${time()} [manager] ${message}`)
1612
+ };
1613
+ /** llbot-core.js next to this bundle; the source entry when run from the source tree with tsx */
1614
+ function coreEntry() {
1615
+ const bundled = path.join(import.meta.dirname, "llbot-core.js");
1616
+ return existsSync(bundled) ? bundled : path.join(import.meta.dirname, "..", "main.ts");
1617
+ }
1618
+ /** Built WebUI assets next to this bundle, or in dist/webui when run from the source tree */
1619
+ function webuiDistDir() {
1620
+ for (const candidate of [path.join(import.meta.dirname, "webui"), path.join(import.meta.dirname, "../../../dist/webui")]) if (existsSync(path.join(candidate, "index.html"))) return candidate;
1621
+ }
1622
+ function displayUrl(host, port) {
1623
+ return `http://${!host || host === "0.0.0.0" || host === "::" ? "127.0.0.1" : host}:${port}/`;
1624
+ }
1625
+ async function main() {
1626
+ const argv = process.argv.slice(2);
1627
+ const args = splitArgs(argv);
1628
+ let release;
1629
+ try {
1630
+ release = await lockManager();
1631
+ } catch (error) {
1632
+ log.error(error.message);
1633
+ process.exit(1);
1634
+ }
1635
+ for (const dir of [LOG_DIR]) mkdirSync(dir, { recursive: true });
1636
+ migrateToInstances({
1637
+ info: (...parts) => log.info(parts.join(" ")),
1638
+ warn: (...parts) => log.warn(parts.join(" "))
1639
+ });
1640
+ const registry = new Registry(DATA_DIR, log);
1641
+ registry.load();
1642
+ let explicitTarget;
1643
+ try {
1644
+ const choice = resolveInstance(argv, process.env);
1645
+ if (choice.reason !== "默认实例") explicitTarget = choice.name;
1646
+ } catch (error) {
1647
+ log.error(error.message);
1648
+ process.exit(1);
1649
+ }
1650
+ let target = explicitTarget ?? registry.defaultInstance();
1651
+ const secret = randomBytes(32).toString("hex");
1652
+ const core = coreEntry();
1653
+ const instances = /* @__PURE__ */ new Map();
1654
+ const running = () => [...instances.values()].filter((instance) => instance.running).length;
1655
+ const statusOf = (name) => instances.get(name)?.status() ?? {
1656
+ name,
1657
+ phase: "stopped"
1658
+ };
1659
+ const coordinator = new PackageCoordinator({
1660
+ send: (name, message) => instances.get(name)?.sendMessage(message) ?? false,
1661
+ pidOf: (name) => instances.get(name)?.status().pid
1662
+ });
1663
+ const instance = (name) => {
1664
+ let existing = instances.get(name);
1665
+ if (existing) return existing;
1666
+ existing = new InstanceProcess(name, {
1667
+ core,
1668
+ args: () => name === target ? [...args.shared, ...args.target] : args.shared,
1669
+ secret,
1670
+ output: (from, line, stream) => {
1671
+ const out = running() > 1 ? `[${from}] ${line}` : line;
1672
+ (stream === "stderr" ? process.stderr : process.stdout).write(out + "\n");
1673
+ },
1674
+ onChange: (status) => {
1675
+ if (status.phase === "running") log.info(`实例 ${name} 已就绪`);
1676
+ else if (status.phase === "stopped") log.info(`实例 ${name} 已停止`);
1677
+ },
1678
+ onMessage: (from, message) => coordinator.onMessage(from, message),
1679
+ onExit: (from) => coordinator.onExit(from),
1680
+ log: log.info
1681
+ });
1682
+ instances.set(name, existing);
1683
+ return existing;
1684
+ };
1685
+ migrateWebuiToken({
1686
+ info: (...parts) => log.info(parts.join(" ")),
1687
+ warn: (...parts) => log.warn(parts.join(" "))
1688
+ }, target);
1689
+ const auth = new GatewayAuth({
1690
+ file: configPaths.webuiToken(),
1691
+ accessLog: path.join(LOG_DIR, "webui_access.log"),
1692
+ log
1693
+ });
1694
+ const envHost = process.env.LLBOT_WEBUI_HOST;
1695
+ const rawEnvPort = Number(process.env.LLBOT_WEBUI_PORT);
1696
+ const envPort = Number.isInteger(rawEnvPort) && rawEnvPort > 0 && rawEnvPort <= 65535 ? rawEnvPort : void 0;
1697
+ const envLocked = [...envHost !== void 0 ? [{
1698
+ path: "webui.host",
1699
+ by: "LLBOT_WEBUI_HOST"
1700
+ }] : [], ...args.webuiPort !== void 0 ? [{
1701
+ path: "webui.port",
1702
+ by: "--webui-port"
1703
+ }] : envPort !== void 0 ? [{
1704
+ path: "webui.port",
1705
+ by: "LLBOT_WEBUI_PORT"
1706
+ }] : []];
1707
+ const effectiveHost = () => envHost ?? registry.load().gateway.host;
1708
+ const effectivePort = () => args.webuiPort ?? envPort ?? registry.load().gateway.port;
1709
+ let listening = effectivePort();
1710
+ let boundHost = effectiveHost();
1711
+ let rebinding = Promise.resolve();
1712
+ const gatewayState = () => ({
1713
+ host: effectiveHost(),
1714
+ port: effectivePort(),
1715
+ listening,
1716
+ envLocked
1717
+ });
1718
+ const managedRunningNames = () => [...instances.values()].filter((child) => child.running).map((child) => child.name);
1719
+ let stopping = false;
1720
+ let stopAutoCheck;
1721
+ let stoppedForUpdate = [];
1722
+ const shutdown = async (code = 0) => {
1723
+ if (stopping) {
1724
+ for (const child of instances.values()) child.stop(0);
1725
+ process.exit(code);
1726
+ }
1727
+ stopping = true;
1728
+ stopAutoCheck?.();
1729
+ if (running()) log.info("正在停止所有实例");
1730
+ await Promise.allSettled([...instances.values()].map((child) => child.stop(25e3)));
1731
+ await gateway.close().catch(() => {});
1732
+ release();
1733
+ process.exit(code);
1734
+ };
1735
+ const installDir = installDirOf(import.meta.dirname);
1736
+ const updater = new CoreUpdater({
1737
+ installDir,
1738
+ registry: () => managerRegistries(registry.instancesDir, [target, registry.defaultInstance()].filter((x) => Boolean(x))),
1739
+ blocker: () => updateBlocker(installDir, {
1740
+ supervised: isSupervised(),
1741
+ ignoreInstances: managedRunningNames()
1742
+ }),
1743
+ beforeReplace: async () => {
1744
+ stoppedForUpdate = managedRunningNames();
1745
+ if (stoppedForUpdate.length) {
1746
+ log.info(`正在停止所有实例以安装更新:${stoppedForUpdate.join("、")}`);
1747
+ await Promise.allSettled(stoppedForUpdate.map((name) => instances.get(name)?.stop(25e3)));
1748
+ }
1749
+ },
1750
+ onReplaceFailed: async () => {
1751
+ for (const name of stoppedForUpdate) if (registry.exists(name)) instance(name).start();
1752
+ stoppedForUpdate = [];
1753
+ },
1754
+ restart: () => {
1755
+ if (!isSupervised()) return false;
1756
+ saveResumeInstances(STATE_DIR, stoppedForUpdate);
1757
+ shutdown(75);
1758
+ return true;
1759
+ },
1760
+ log
1761
+ });
1762
+ const gateway = new Gateway({
1763
+ auth,
1764
+ secret,
1765
+ lookup: (name) => {
1766
+ if (!instances.has(name) && !registry.exists(name)) return void 0;
1767
+ const status = statusOf(name);
1768
+ return {
1769
+ name,
1770
+ phase: status.phase,
1771
+ port: status.webuiPort
1772
+ };
1773
+ },
1774
+ defaultInstance: () => target ?? registry.defaultInstance() ?? "",
1775
+ manager: createManagerApi({
1776
+ registry,
1777
+ selected: () => target ?? registry.defaultInstance() ?? "",
1778
+ statusOf,
1779
+ recentOutput: (name) => instances.get(name)?.recentOutput() ?? [],
1780
+ instance,
1781
+ isLockedExternal: async (name) => !instances.get(name)?.running && (await runningInstances()).includes(name),
1782
+ onRenamed: (from, to) => {
1783
+ instances.delete(from);
1784
+ if (target === from) target = to;
1785
+ },
1786
+ onRemoved: (name) => {
1787
+ instances.delete(name);
1788
+ if (target === name) target = registry.defaultInstance();
1789
+ },
1790
+ gatewayState,
1791
+ onGatewayChanged: (nextHost, nextPort) => {
1792
+ rebinding = rebinding.then(async () => {
1793
+ const previousHost = boundHost;
1794
+ const previousPort = listening;
1795
+ try {
1796
+ listening = await gateway.rebind(nextHost, nextPort);
1797
+ boundHost = nextHost;
1798
+ log.info(`Webui 服务器已重启 ${nextHost || "0.0.0.0"}:${listening}`);
1799
+ log.info(`所有实例共用这个 WebUI 地址:${displayUrl(nextHost, listening)}`);
1800
+ } catch (error) {
1801
+ log.error(`WebUI 无法改到 ${nextHost || "0.0.0.0"}:${nextPort}:${error.message},恢复原监听地址`);
1802
+ try {
1803
+ listening = await gateway.rebind(previousHost, previousPort);
1804
+ boundHost = previousHost;
1805
+ } catch (recoverError) {
1806
+ log.error(`恢复原监听地址失败:${recoverError.message}`);
1807
+ }
1808
+ }
1809
+ });
1810
+ }
1811
+ }),
1812
+ coreUpdate: createCoreUpdateHandler(updater),
1813
+ webuiDir: webuiDistDir(),
1814
+ log
1815
+ });
1816
+ try {
1817
+ listening = await gateway.listen(boundHost, effectivePort());
1818
+ } catch (error) {
1819
+ log.error(`WebUI 无法监听 ${boundHost || "0.0.0.0"}:${effectivePort()}:${error.message}`);
1820
+ release();
1821
+ process.exit(1);
1822
+ }
1823
+ log.info(`Webui 服务器已启动 ${boundHost || "0.0.0.0"}:${listening}`);
1824
+ log.info(`所有实例共用这个 WebUI 地址:${displayUrl(boundHost, listening)}`);
1825
+ updater.cleanup().catch((error) => log.warn(error instanceof Error ? error.message : String(error)));
1826
+ stopAutoCheck = scheduleAutoCheck(updater, { log });
1827
+ const resumed = consumeResumeInstances(STATE_DIR).filter((name) => registry.exists(name));
1828
+ const autostart = [.../* @__PURE__ */ new Set([
1829
+ ...explicitTarget ? [explicitTarget] : [],
1830
+ ...registry.autostart(),
1831
+ ...resumed
1832
+ ])];
1833
+ for (const name of autostart) instance(name).start();
1834
+ if (autostart.length === 0) log.info(registry.list().length === 0 ? "当前还没有实例,请在 WebUI 的「实例管理」中新建实例" : "没有设为自启的实例,可在 WebUI 的「实例管理」中手动启动");
1835
+ process.on("SIGINT", () => void shutdown());
1836
+ process.on("SIGTERM", () => void shutdown());
1837
+ if (process.platform !== "win32") process.on("SIGHUP", () => void shutdown());
1838
+ const parent = parentPidOf(argv);
1839
+ if (!Number.isNaN(parent) && parent !== process.pid) {
1840
+ const timer = setInterval(() => {
1841
+ try {
1842
+ process.kill(parent, 0);
1843
+ } catch (error) {
1844
+ if (error.code !== "ESRCH") return;
1845
+ clearInterval(timer);
1846
+ shutdown();
1847
+ }
1848
+ }, 1e3);
1849
+ timer.unref();
1850
+ }
1851
+ }
1852
+ main().catch((error) => {
1853
+ log.error(error instanceof Error ? error.stack ?? error.message : String(error));
1854
+ process.exit(1);
1855
+ });
1856
+ //#endregion
1857
+ export {};
1858
+
1859
+ //# sourceMappingURL=llbot-manager.js.map