@cmach_socket/opencode-qq-bot 0.8.0 → 0.9.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,345 @@
1
+ import { readFile } from "node:fs/promises"
2
+ import { join } from "node:path"
3
+ import { serveStatic } from "@hono/node-server/serve-static"
4
+ import { Hono } from "hono"
5
+ import { getCookie, setCookie } from "hono/cookie"
6
+ import { csrf } from "hono/csrf"
7
+ import { secureHeaders } from "hono/secure-headers"
8
+ import { streamSSE } from "hono/streaming"
9
+ import type { ConfigController } from "../config/live"
10
+ import { CONFIG_FIELDS, CONFIG_GROUPS } from "../config/fields"
11
+ import {
12
+ configJsonSchema,
13
+ createStrictFieldSchema,
14
+ getConfigValue,
15
+ requiredFieldProblem,
16
+ } from "../config/registry"
17
+ import { readLogTail, subscribeLogs, type LogEntry } from "../logger"
18
+ import { PanelAuth, SESSION_COOKIE } from "./auth"
19
+ import type { ModelProvider } from "./models"
20
+ import { collectStatus } from "./status"
21
+ import type { PanelRuntime } from "./runtime"
22
+
23
+ /**
24
+ * 面板的 HTTP 接口。
25
+ *
26
+ * 鉴权两条路:`Authorization: Bearer <token>` 供命令行与 curl 用,
27
+ * 浏览器先 `POST /api/login` 换会话 Cookie,之后自动带上。
28
+ */
29
+
30
+ /** 安全的方法:不需要 CSRF 校验。 */
31
+ const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"])
32
+
33
+ /** 面板应用的依赖。 */
34
+ export interface PanelAppOptions {
35
+ /** 令牌与会话管理。 */
36
+ auth: PanelAuth
37
+ /** 配置控制器:读写与热更新都走它。 */
38
+ controller: ConfigController
39
+ /** 运行时句柄。 */
40
+ runtime: PanelRuntime
41
+ /** 可用模型列表。 */
42
+ models: ModelProvider
43
+ /** 前端构建产物目录;没有就不托管静态资源。 */
44
+ staticDir?: string
45
+ }
46
+
47
+ /** 状态推送的间隔(毫秒)。 */
48
+ const STATUS_INTERVAL_MS = 2000
49
+
50
+ /** 单个配置项在接口里的样子。 */
51
+ interface ConfigFieldView {
52
+ /** 配置路径。 */
53
+ path: string
54
+ /** 生效值;敏感字段没有这一项。 */
55
+ value?: unknown
56
+ /** 文件里写的值;敏感字段没有这一项。 */
57
+ fileValue?: unknown
58
+ /** 值来自哪里:`file` 或 `default`。 */
59
+ source: "file" | "default"
60
+ /** 是否敏感字段。 */
61
+ secret: boolean
62
+ /** 是否热更新。 */
63
+ hot: boolean
64
+ /** 敏感字段只给这个:有没有值。 */
65
+ hasValue?: boolean
66
+ }
67
+
68
+ /** 构造面板应用。 */
69
+ export function createPanelApp(options: PanelAppOptions): Hono {
70
+ const app = new Hono()
71
+ const { auth, controller, runtime } = options
72
+
73
+ // 静态资源带安全响应头:面板是本地工具,但浏览器照样要按 CSP 走。
74
+ app.use(
75
+ "*",
76
+ secureHeaders({
77
+ contentSecurityPolicy: {
78
+ defaultSrc: ["'self'"],
79
+ scriptSrc: ["'self'"],
80
+ styleSrc: ["'self'", "'unsafe-inline'"],
81
+ imgSrc: ["'self'", "data:"],
82
+ fontSrc: ["'self'", "data:"],
83
+ connectSrc: ["'self'"],
84
+ objectSrc: ["'none'"],
85
+ baseUri: ["'self'"],
86
+ frameAncestors: ["'none'"],
87
+ },
88
+ // 面板走本机 http,HSTS 没有意义。
89
+ strictTransportSecurity: false,
90
+ }),
91
+ )
92
+
93
+ // 写接口校验 Origin:带 Origin 的请求必须同源,不带的(curl)放行。
94
+ app.use("/api/*", async (c, next) => {
95
+ if (SAFE_METHODS.has(c.req.method)) return await next()
96
+ const origin = c.req.header("Origin")
97
+ if (origin) {
98
+ let expected = ""
99
+ try {
100
+ expected = new URL(c.req.url).origin
101
+ } catch {
102
+ expected = ""
103
+ }
104
+ if (origin !== expected) {
105
+ return c.json({ error: "forbidden", message: "跨站请求已被拒绝" }, 403)
106
+ }
107
+ }
108
+ return await next()
109
+ })
110
+ // 表单类内容类型再过一遍 hono 自带的 CSRF 校验。
111
+ app.use("/api/*", csrf({ origin: (origin, c) => origin === new URL(c.req.url).origin }))
112
+
113
+ // 鉴权:Bearer 令牌或会话 Cookie。
114
+ app.use("/api/*", async (c, next) => {
115
+ if (c.req.path === "/api/login") return await next()
116
+ const header = c.req.header("Authorization")
117
+ if (header?.startsWith("Bearer ")) {
118
+ if (auth.matches(header.slice("Bearer ".length).trim())) return await next()
119
+ return c.json({ error: "unauthorized", message: "令牌不正确" }, 401)
120
+ }
121
+ if (auth.valid(getCookie(c, SESSION_COOKIE))) return await next()
122
+ return c.json({ error: "unauthorized", message: "未授权:请先登录" }, 401)
123
+ })
124
+
125
+ // 用令牌换会话 Cookie。
126
+ app.post("/api/login", async (c) => {
127
+ const body = await readJson(c.req.raw)
128
+ const token =
129
+ body && typeof body === "object" && !Array.isArray(body)
130
+ ? (body as Record<string, unknown>).token
131
+ : undefined
132
+ if (typeof token !== "string" || !auth.matches(token)) {
133
+ return c.json({ error: "invalid_token", message: "令牌不正确" }, 401)
134
+ }
135
+ setCookie(c, SESSION_COOKIE, auth.issue(), {
136
+ httpOnly: true,
137
+ sameSite: "Strict",
138
+ path: "/",
139
+ maxAge: 60 * 60 * 24 * 30,
140
+ })
141
+ return c.json({ ok: true })
142
+ })
143
+
144
+ // 字段元数据与 JSON Schema:前端据此渲染表单。
145
+ app.get("/api/config/schema", (c) => {
146
+ return c.json({
147
+ version: 1,
148
+ groups: CONFIG_GROUPS,
149
+ fields: CONFIG_FIELDS,
150
+ jsonSchema: configJsonSchema(),
151
+ })
152
+ })
153
+
154
+ // 生效值、文件值与每字段来源。
155
+ app.get("/api/config", (c) => {
156
+ return c.json({ fields: configView(controller) })
157
+ })
158
+
159
+ // 提交变更:后端用同一份规则校验后落盘。
160
+ app.put("/api/config", async (c) => {
161
+ const contentType = c.req.header("Content-Type") ?? ""
162
+ if (!contentType.toLowerCase().includes("application/json")) {
163
+ return c.json({ error: "unsupported_media_type", message: "只接受 JSON 请求体" }, 415)
164
+ }
165
+ const body = await readJson(c.req.raw)
166
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
167
+ return c.json({ error: "invalid_body", message: "请求体必须是一个 JSON 对象" }, 400)
168
+ }
169
+ const patch = body as Record<string, unknown>
170
+ const problems = validatePatch(patch)
171
+ if (problems.length > 0) {
172
+ return c.json(
173
+ { error: "validation_failed", message: "配置校验不通过", fields: problems },
174
+ 400,
175
+ )
176
+ }
177
+ try {
178
+ const result = await controller.applyPatch(patch)
179
+ return c.json({
180
+ ok: true,
181
+ restartRequired: result.restartRequired,
182
+ fields: configView(controller),
183
+ })
184
+ } catch (error) {
185
+ return c.json(
186
+ {
187
+ error: "write_failed",
188
+ message: error instanceof Error ? error.message : String(error),
189
+ },
190
+ 500,
191
+ )
192
+ }
193
+ })
194
+
195
+ // 可用模型列表。
196
+ app.get("/api/models", async (c) => {
197
+ try {
198
+ return c.json({ models: await options.models.list() })
199
+ } catch (error) {
200
+ return c.json(
201
+ { error: "models_failed", message: error instanceof Error ? error.message : String(error) },
202
+ 502,
203
+ )
204
+ }
205
+ })
206
+
207
+ // 运行状态快照。
208
+ app.get("/api/status", async (c) => {
209
+ return c.json(await collectStatus(runtime))
210
+ })
211
+
212
+ // 日志尾部。
213
+ app.get("/api/logs", (c) => {
214
+ const limit = Number(c.req.query("limit") ?? "200")
215
+ const level = c.req.query("level")
216
+ const entries = readLogTail({
217
+ ...(Number.isFinite(limit) ? { limit } : {}),
218
+ ...(level === "debug" || level === "info" || level === "warn" || level === "error"
219
+ ? { level }
220
+ : {}),
221
+ })
222
+ return c.json({ entries })
223
+ })
224
+
225
+ // SSE:状态、配置变更与日志推送。
226
+ app.get("/api/stream", (c) => {
227
+ return streamSSE(c, async (stream) => {
228
+ let alive = true
229
+ const write = async (event: string, data: unknown) => {
230
+ if (!alive) return
231
+ try {
232
+ await stream.writeSSE({ event, data: JSON.stringify(data) })
233
+ } catch {
234
+ alive = false
235
+ }
236
+ }
237
+ const unsubscribeLogs = subscribeLogs((entry: LogEntry) => {
238
+ void write("log", entry)
239
+ })
240
+ const unsubscribeConfig = controller.onChange(() => {
241
+ void write("config", { fields: configView(controller) })
242
+ })
243
+ const timer = setInterval(() => {
244
+ void collectStatus(runtime)
245
+ .then((status) => write("status", status))
246
+ .catch(() => undefined)
247
+ }, STATUS_INTERVAL_MS)
248
+ timer.unref?.()
249
+ const close = () => {
250
+ alive = false
251
+ clearInterval(timer)
252
+ unsubscribeLogs()
253
+ unsubscribeConfig()
254
+ }
255
+ stream.onAbort(close)
256
+ await write("status", await collectStatus(runtime))
257
+ // 保持连接,直到客户端断开;`onAbort` 负责清理计时器与订阅。
258
+ while (alive) await stream.sleep(1000)
259
+ close()
260
+ })
261
+ })
262
+
263
+ // 静态资源与单页应用。
264
+ if (options.staticDir) {
265
+ const root = options.staticDir
266
+ app.use("/*", serveStatic({ root, rewriteRequestPath: (path) => path }))
267
+ app.notFound(async (c) => {
268
+ if (c.req.path.startsWith("/api/")) {
269
+ return c.json({ error: "not_found", message: "接口不存在" }, 404)
270
+ }
271
+ const index = join(root, "index.html")
272
+ try {
273
+ const html = await readFile(index, "utf8")
274
+ return c.html(html)
275
+ } catch {
276
+ return c.text("前端构建产物不存在:请先执行 bun run web:build", 404)
277
+ }
278
+ })
279
+ }
280
+
281
+ return app
282
+ }
283
+
284
+ /** 读取 JSON 请求体;解析失败返回 undefined。 */
285
+ async function readJson(request: Request): Promise<unknown> {
286
+ try {
287
+ return await request.json()
288
+ } catch {
289
+ return undefined
290
+ }
291
+ }
292
+
293
+ /** 逐字段的生效值视图。 */
294
+ function configView(controller: ConfigController): ConfigFieldView[] {
295
+ const config = controller.current
296
+ const raw = controller.file
297
+ return CONFIG_FIELDS.map((field) => {
298
+ const value = config ? getConfigValue(config, field.path) : undefined
299
+ const fileValue = getConfigValue(raw, field.path)
300
+ const fromFile = fileValue !== undefined
301
+ const base = {
302
+ path: field.path,
303
+ source: fromFile ? ("file" as const) : ("default" as const),
304
+ secret: field.secret === true,
305
+ hot: field.hot === true,
306
+ }
307
+ if (field.secret) {
308
+ const hasValue =
309
+ typeof value === "string" ? value.length > 0 : value !== undefined && value !== null
310
+ return { ...base, hasValue }
311
+ }
312
+ return {
313
+ ...base,
314
+ value,
315
+ ...(fromFile ? { fileValue } : {}),
316
+ }
317
+ })
318
+ }
319
+
320
+ /** 校验稀疏补丁:字段必须存在,值必须合法。 */
321
+ function validatePatch(patch: Record<string, unknown>): Array<{ path: string; message: string }> {
322
+ const problems: Array<{ path: string; message: string }> = []
323
+ for (const [path, value] of Object.entries(patch)) {
324
+ const field = CONFIG_FIELDS.find((entry) => entry.path === path)
325
+ if (!field) {
326
+ problems.push({ path, message: "未知配置项" })
327
+ continue
328
+ }
329
+ if (value === null) {
330
+ const problem = requiredFieldProblem(path, value)
331
+ if (problem) problems.push({ path, message: problem })
332
+ continue
333
+ }
334
+ const schema = createStrictFieldSchema(field)
335
+ const result = schema.safeParse(value)
336
+ if (!result.success) {
337
+ const message = result.error.issues
338
+ .map((issue) => issue.message)
339
+ .filter((text) => text.length > 0)
340
+ .join(";")
341
+ problems.push({ path, message: message.length > 0 ? message : "取值不合法" })
342
+ }
343
+ }
344
+ return problems
345
+ }
@@ -0,0 +1,65 @@
1
+ import { createHash, randomBytes, timingSafeEqual } from "node:crypto"
2
+
3
+ /**
4
+ * 面板鉴权:单令牌 + 会话 Cookie。
5
+ *
6
+ * 面板是单用户本地工具:一个令牌换一张会话 Cookie 就够了。
7
+ */
8
+
9
+ /** 会话 Cookie 的名字。 */
10
+ export const SESSION_COOKIE = "qqbot_session"
11
+
12
+ /** 令牌哈希。 */
13
+ function digest(value: string): Buffer {
14
+ return createHash("sha256").update(value, "utf8").digest()
15
+ }
16
+
17
+ /** 令牌与会话管理。 */
18
+ export class PanelAuth {
19
+ /** 令牌哈希:内存里不留明文。 */
20
+ private tokenHash: Buffer
21
+ /** 已签发的会话 id。 */
22
+ private readonly sessions = new Set<string>()
23
+
24
+ constructor(token: string) {
25
+ this.tokenHash = digest(token)
26
+ }
27
+
28
+ /**
29
+ * 令牌是否正确。
30
+ *
31
+ * 比较等长的 sha256 哈希,恒定时间,不泄露长度以外的信息。
32
+ */
33
+ matches(candidate: string): boolean {
34
+ if (typeof candidate !== "string" || candidate.length === 0) return false
35
+ return timingSafeEqual(this.tokenHash, digest(candidate))
36
+ }
37
+
38
+ /** 签发一个会话 id。 */
39
+ issue(): string {
40
+ const id = randomBytes(24).toString("hex")
41
+ this.sessions.add(id)
42
+ return id
43
+ }
44
+
45
+ /** 会话是否有效。 */
46
+ valid(session: string | undefined): boolean {
47
+ if (typeof session !== "string" || session.length === 0) return false
48
+ return this.sessions.has(session)
49
+ }
50
+
51
+ /**
52
+ * 更换令牌。
53
+ *
54
+ * 旧令牌与所有已签发的会话立刻作废。
55
+ */
56
+ rotate(token: string): void {
57
+ this.tokenHash = digest(token)
58
+ this.sessions.clear()
59
+ }
60
+
61
+ /** 作废全部会话。 */
62
+ clear(): void {
63
+ this.sessions.clear()
64
+ }
65
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * 可用模型列表。
3
+ *
4
+ * 候选模型来自 OpenCode 的 provider 配置与模型目录,不在插件的配置里;
5
+ * 插件只是借 `ctx.model` 转述,模型列表变了要重载插件才会同步。
6
+ */
7
+
8
+ /** 面板展示的模型。 */
9
+ export interface ModelInfo {
10
+ /** provider id。 */
11
+ providerID: string
12
+ /** 模型 id。 */
13
+ id: string
14
+ /** 展示名。 */
15
+ name: string
16
+ /** 是否是 OpenCode 当前的默认模型。 */
17
+ default: boolean
18
+ }
19
+
20
+ /** 模型列表的来源。 */
21
+ export interface ModelProvider {
22
+ /** 取当前可用的模型。 */
23
+ list(): Promise<ModelInfo[]>
24
+ }
25
+
26
+ /** OpenCode 的模型接口:只用 list 与 default 两个方法。 */
27
+ interface ModelApiLike {
28
+ list(): Promise<{ data?: Array<{ providerID?: string; id?: string; name?: string }> }>
29
+ default(): Promise<{ data?: { providerID?: string; id?: string } | null }>
30
+ }
31
+
32
+ /**
33
+ * 把 OpenCode 的模型接口包成面板要的形状。
34
+ *
35
+ * @param api `ctx.model`。
36
+ */
37
+ export function createModelProvider(api: ModelApiLike): ModelProvider {
38
+ return {
39
+ async list(): Promise<ModelInfo[]> {
40
+ const listed = await api.list()
41
+ const fallback = await api.default().catch(() => ({ data: null }))
42
+ const current = fallback.data
43
+ const models = listed.data ?? []
44
+ return models.map((model) => ({
45
+ providerID: model.providerID ?? "",
46
+ id: model.id ?? "",
47
+ name: model.name ?? `${model.providerID ?? ""}/${model.id ?? ""}`,
48
+ default:
49
+ current !== undefined &&
50
+ current !== null &&
51
+ current.providerID === model.providerID &&
52
+ current.id === model.id,
53
+ }))
54
+ },
55
+ }
56
+ }
@@ -0,0 +1,51 @@
1
+ import type { QQBotConfig } from "../config"
2
+ import type { BotHome } from "../home"
3
+ import type { Logger } from "../logger"
4
+ import type { DiaryScheduler } from "../diary/scheduler"
5
+ import type { ChatOverrides } from "../overrides"
6
+ import type { QQClient } from "../naplink/client"
7
+ import type { SendRateLimiter } from "../rate-limit"
8
+ import type { SessionManager } from "../session/manager"
9
+ import type { ToolPolicy } from "../tools/policy"
10
+ import type { Tracer } from "../trace"
11
+
12
+ /**
13
+ * 面板能看到的运行时句柄。
14
+ *
15
+ * 插件的运行时是逐步搭起来的(连接、会话、追踪、日记……),
16
+ * 这里把已经就绪的句柄聚在一起,状态快照按需取用。
17
+ */
18
+ export class PanelRuntime {
19
+ /** 进程启动时间(毫秒)。 */
20
+ readonly startedAt = Date.now()
21
+ /** 插件版本。 */
22
+ version = "unknown"
23
+ /** 生效中的配置。 */
24
+ config: QQBotConfig
25
+ /** 机器人工作目录。 */
26
+ home: BotHome
27
+ /** 日志器。 */
28
+ logger: Logger
29
+ /** `opencode.json` 里的 agent,只读展示。 */
30
+ agent?: string
31
+ /** NapCat 连接。 */
32
+ client?: QQClient
33
+ /** 会话管理。 */
34
+ manager?: SessionManager
35
+ /** 出站限流。 */
36
+ limiter?: SendRateLimiter
37
+ /** 调用链追踪。 */
38
+ tracer?: Tracer
39
+ /** 日记调度。 */
40
+ diary?: DiaryScheduler
41
+ /** 工具策略。 */
42
+ policy?: ToolPolicy
43
+ /** 会话行为覆盖。 */
44
+ overrides?: ChatOverrides
45
+
46
+ constructor(options: { config: QQBotConfig; home: BotHome; logger: Logger }) {
47
+ this.config = options.config
48
+ this.home = options.home
49
+ this.logger = options.logger
50
+ }
51
+ }
@@ -0,0 +1,185 @@
1
+ import { createAdaptorServer, type ServerType } from "@hono/node-server"
2
+ import { existsSync } from "node:fs"
3
+ import { join } from "node:path"
4
+ import type { ConfigController } from "../config/live"
5
+ import { packageRoot } from "../seed"
6
+ import type { Logger } from "../logger"
7
+ import { createPanelApp } from "./api"
8
+ import { PanelAuth } from "./auth"
9
+ import type { ModelProvider } from "./models"
10
+ import type { PanelRuntime } from "./runtime"
11
+
12
+ /**
13
+ * 面板的 HTTP 服务。
14
+ *
15
+ * 随插件启停:插件被 OpenCode 卸载时服务一并关闭,不留残留端口。
16
+ */
17
+
18
+ /** 面板服务的依赖。 */
19
+ export interface PanelServerOptions {
20
+ /** 配置控制器。 */
21
+ controller: ConfigController
22
+ /** 运行时句柄。 */
23
+ runtime: PanelRuntime
24
+ /** 可用模型列表。 */
25
+ models: ModelProvider
26
+ /** 日志器。 */
27
+ logger: Logger
28
+ /** 端口被占用时的重试次数与间隔(毫秒)。 */
29
+ retry?: { times: number; intervalMs: number }
30
+ }
31
+
32
+ /** 前端构建产物目录。 */
33
+ export function panelStaticDir(): string {
34
+ return join(packageRoot, "web", "dist")
35
+ }
36
+
37
+ /** 端口被占用时的重试次数与间隔(毫秒)。 */
38
+ const PORT_RETRY_TIMES = 5
39
+ const PORT_RETRY_INTERVAL_MS = 500
40
+
41
+ export class PanelServer {
42
+ private server: ServerType | undefined
43
+ private auth: PanelAuth
44
+ /** 鉴权当前认的令牌。 */
45
+ private token: string
46
+ private unsubscribe: (() => void) | undefined
47
+ /** 当前监听的地址与端口。 */
48
+ private listening: { host: string; port: number } | undefined
49
+ /** 端口被占用时的重试策略。 */
50
+ private readonly retry: { times: number; intervalMs: number }
51
+
52
+ constructor(private readonly options: PanelServerOptions) {
53
+ this.token = options.runtime.config.panel.token
54
+ this.auth = new PanelAuth(this.token)
55
+ this.retry = options.retry ?? { times: PORT_RETRY_TIMES, intervalMs: PORT_RETRY_INTERVAL_MS }
56
+ }
57
+
58
+ /** 令牌与会话管理。 */
59
+ get sessions(): PanelAuth {
60
+ return this.auth
61
+ }
62
+
63
+ /**
64
+ * 启动服务。
65
+ *
66
+ * 订阅配置变化与面板是否启用无关:启用、地址、端口都由配置决定,
67
+ * 面板关着的时候也得盯着配置,改成启用之后要能自己起来。
68
+ */
69
+ async start(): Promise<void> {
70
+ this.unsubscribe ??= this.options.controller.onChange(() => {
71
+ void this.reconcile()
72
+ })
73
+ await this.reconcile()
74
+ }
75
+
76
+ /** 停止服务:退订配置变化并关闭 HTTP 服务。 */
77
+ async stop(): Promise<void> {
78
+ this.unsubscribe?.()
79
+ this.unsubscribe = undefined
80
+ await this.closeServer()
81
+ }
82
+
83
+ /** 配置变了:令牌、是否启用、地址或端口都要跟着调整。 */
84
+ private async reconcile(): Promise<void> {
85
+ const config = this.options.runtime.config
86
+ // 令牌先换:面板关着的时候换了令牌,启用后也要认新的。
87
+ if (config.panel.token !== this.token) {
88
+ this.token = config.panel.token
89
+ this.auth.rotate(config.panel.token)
90
+ this.options.logger.info("面板令牌已更新,已签发的会话全部作废")
91
+ }
92
+ if (!config.panel.enabled) {
93
+ await this.closeServer()
94
+ return
95
+ }
96
+ const host = config.panel.host
97
+ const port = config.panel.port
98
+ if (this.listening && this.listening.host === host && this.listening.port === port) return
99
+ await this.closeServer()
100
+ await this.listen()
101
+ }
102
+
103
+ /** 关掉 HTTP 服务。 */
104
+ private async closeServer(): Promise<void> {
105
+ const server = this.server
106
+ this.server = undefined
107
+ this.listening = undefined
108
+ if (!server) return
109
+ await new Promise<void>((resolve) => {
110
+ server.close(() => resolve())
111
+ // SSE 的连接不会自己断,close 会一直等;强制掐掉,免得卸载卡住。
112
+ if ("closeAllConnections" in server) server.closeAllConnections()
113
+ })
114
+ }
115
+
116
+ /** 真正开始监听。 */
117
+ private async listen(): Promise<void> {
118
+ const config = this.options.runtime.config
119
+ const host = config.panel.host
120
+ const port = config.panel.port
121
+ const staticDir = panelStaticDir()
122
+ const app = createPanelApp({
123
+ auth: this.auth,
124
+ controller: this.options.controller,
125
+ runtime: this.options.runtime,
126
+ models: this.options.models,
127
+ ...(existsSync(staticDir) ? { staticDir } : {}),
128
+ })
129
+ const server = await this.bind(app, host, port)
130
+ server.on("error", (error: Error) => {
131
+ this.options.logger.error("状态面板服务出错", error)
132
+ })
133
+ server.unref?.()
134
+ this.server = server
135
+ this.listening = { host, port }
136
+ this.options.logger.info(`状态面板已启动:http://${host}:${port}`)
137
+ if (!existsSync(staticDir)) {
138
+ this.options.logger.warn("面板前端产物不存在,只有接口可用", "请执行 bun run web:build")
139
+ }
140
+ }
141
+
142
+ /**
143
+ * 监听端口。
144
+ *
145
+ * 端口被占用时 `http.Server` 是异步抛错的,不显式接住就会变成未捕获异常
146
+ * 把整个进程带下去;这里自己接住并重试:上一个实例刚退出时端口还没释放,
147
+ * 等一下就能接上。
148
+ */
149
+ private async bind(app: ReturnType<typeof createPanelApp>, host: string, port: number) {
150
+ for (let attempt = 0; ; attempt++) {
151
+ const server = createAdaptorServer({ fetch: app.fetch, hostname: host })
152
+ try {
153
+ await new Promise<void>((resolve, reject) => {
154
+ const onError = (error: Error) => {
155
+ server.off("listening", onListening)
156
+ reject(error)
157
+ }
158
+ const onListening = () => {
159
+ server.off("error", onError)
160
+ resolve()
161
+ }
162
+ server.once("error", onError)
163
+ server.once("listening", onListening)
164
+ server.listen(port, host)
165
+ })
166
+ return server
167
+ } catch (error) {
168
+ server.close()
169
+ const code = (error as NodeJS.ErrnoException).code
170
+ if (code !== "EADDRINUSE" || attempt >= this.retry.times) throw error
171
+ this.options.logger.warn(
172
+ `面板端口 ${host}:${port} 被占用,稍后重试(${attempt + 1}/${this.retry.times})`,
173
+ )
174
+ await delay(this.retry.intervalMs)
175
+ }
176
+ }
177
+ }
178
+ }
179
+
180
+ /** 等一会儿再继续。 */
181
+ function delay(ms: number): Promise<void> {
182
+ return new Promise((resolve) => {
183
+ setTimeout(resolve, ms)
184
+ })
185
+ }