@cmach_socket/opencode-qq-bot 0.7.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.
- package/NOTICE +48 -15
- package/README.md +220 -115
- package/package.json +10 -1
- package/src/cleanup.ts +1 -0
- package/src/commands.ts +2 -0
- package/src/config/fields.ts +780 -0
- package/src/config/live.ts +161 -0
- package/src/config/registry.ts +654 -0
- package/src/config/store.ts +175 -0
- package/src/config/types.ts +253 -0
- package/src/config.ts +77 -1023
- package/src/diary/collector.ts +28 -14
- package/src/diary/command.ts +24 -2
- package/src/diary/paths.ts +27 -0
- package/src/diary/scheduler.ts +63 -14
- package/src/diary/scope.ts +27 -0
- package/src/diary/store.ts +48 -4
- package/src/diary/summary.ts +33 -5
- package/src/home.ts +11 -16
- package/src/index.ts +777 -644
- package/src/logger.ts +104 -1
- package/src/model-view.ts +3 -1
- package/src/naplink/client.ts +16 -0
- package/src/panel/api.ts +345 -0
- package/src/panel/auth.ts +65 -0
- package/src/panel/models.ts +56 -0
- package/src/panel/runtime.ts +51 -0
- package/src/panel/server.ts +185 -0
- package/src/panel/status.ts +201 -0
- package/src/rate-limit.ts +46 -0
- package/src/runtime/claim.ts +37 -0
- package/src/runtime/start.ts +55 -0
- package/src/sensitive.ts +6 -1
- package/src/session/find.ts +44 -10
- package/src/session/manager.ts +118 -19
- package/src/session/prompt.ts +1 -1
- package/src/text.ts +34 -0
- package/src/tools/policy.ts +16 -1
- package/src/tools/qq.ts +90 -38
- package/src/tools/send-guard.ts +2 -2
- package/src/tui-commands.ts +1 -1
- package/web/dist/assets/index-7eMQEM7-.css +1 -0
- package/web/dist/assets/index-DCkgUY7y.js +15 -0
- package/web/dist/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
- package/web/dist/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
- package/web/dist/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
- package/web/dist/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
- package/web/dist/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
- package/web/dist/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
- package/web/dist/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
- package/web/dist/index.html +13 -0
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import { targetKey } from "../chat"
|
|
2
|
+
import { defaultLogDir } from "../logger"
|
|
3
|
+
import type { TraceSpan } from "../trace"
|
|
4
|
+
import type { PanelRuntime } from "./runtime"
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* 运行状态快照。
|
|
8
|
+
*
|
|
9
|
+
* `/api/status` 与 SSE 推送共用这一份实现:面板看到的和命令输出看到的是同一套数据。
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** 状态快照。 */
|
|
13
|
+
export interface StatusSnapshot {
|
|
14
|
+
/** 插件版本。 */
|
|
15
|
+
version: string
|
|
16
|
+
/** 进程启动时间(毫秒)。 */
|
|
17
|
+
startedAt: number
|
|
18
|
+
/** 已经跑了多久(毫秒)。 */
|
|
19
|
+
uptimeMs: number
|
|
20
|
+
/** 运行时信息。 */
|
|
21
|
+
runtime: {
|
|
22
|
+
/** 机器人工作目录。 */
|
|
23
|
+
home: string
|
|
24
|
+
/** 日志目录。 */
|
|
25
|
+
logDir: string
|
|
26
|
+
/** `opencode.json` 里的 agent。 */
|
|
27
|
+
agent?: string
|
|
28
|
+
/** 配置里选的模型。 */
|
|
29
|
+
model?: string
|
|
30
|
+
/** 面板自身的监听信息。 */
|
|
31
|
+
panel: { enabled: boolean; host: string; port: number }
|
|
32
|
+
}
|
|
33
|
+
/** 连接概览。 */
|
|
34
|
+
connection: {
|
|
35
|
+
/** NapCat 是否连着。 */
|
|
36
|
+
connected: boolean
|
|
37
|
+
/** 机器人的 QQ 号。 */
|
|
38
|
+
selfId?: string
|
|
39
|
+
/** 重连次数。 */
|
|
40
|
+
reconnects: number
|
|
41
|
+
/** 最后一次重连的时间(毫秒)。 */
|
|
42
|
+
lastReconnectAt?: number
|
|
43
|
+
}
|
|
44
|
+
/** 各聊天的会话状态。 */
|
|
45
|
+
sessions: Array<{
|
|
46
|
+
/** 聊天目标键,例如 `group:123`。 */
|
|
47
|
+
target: string
|
|
48
|
+
/** 绑定的上游会话。 */
|
|
49
|
+
sessionID?: string
|
|
50
|
+
/** 当前是否有一轮在跑。 */
|
|
51
|
+
busy: boolean
|
|
52
|
+
/** 缓存中的消息条数。 */
|
|
53
|
+
buffered: number
|
|
54
|
+
/** 是否在等待重试。 */
|
|
55
|
+
pending: boolean
|
|
56
|
+
/** 唤醒方式,来自会话覆盖。 */
|
|
57
|
+
wake?: string
|
|
58
|
+
/** 是否允许主动说话。 */
|
|
59
|
+
proactive?: boolean
|
|
60
|
+
}>
|
|
61
|
+
/** 出站限流用量。 */
|
|
62
|
+
rateLimit: Array<{
|
|
63
|
+
/** 计数维度,通常是目标键。 */
|
|
64
|
+
scope: string
|
|
65
|
+
/** 每分钟上限。 */
|
|
66
|
+
maxPerMinute: number
|
|
67
|
+
/** 每小时上限。 */
|
|
68
|
+
maxPerHour: number
|
|
69
|
+
/** 这一分钟已发多少条。 */
|
|
70
|
+
usedPerMinute: number
|
|
71
|
+
/** 这一小时已发多少条。 */
|
|
72
|
+
usedPerHour: number
|
|
73
|
+
/** 这一分钟还剩多少条。 */
|
|
74
|
+
minuteLeft: number
|
|
75
|
+
/** 这一小时还剩多少条。 */
|
|
76
|
+
hourLeft: number
|
|
77
|
+
}>
|
|
78
|
+
/** 最近的调用链追踪节点。 */
|
|
79
|
+
traces: TraceSpan[]
|
|
80
|
+
/** 日记调度。 */
|
|
81
|
+
diary: {
|
|
82
|
+
/** 是否启用。 */
|
|
83
|
+
enabled: boolean
|
|
84
|
+
/** 每天几点生成总结。 */
|
|
85
|
+
summaryTime: string
|
|
86
|
+
/** 下次轮询时间(毫秒)。 */
|
|
87
|
+
nextRunAt?: number
|
|
88
|
+
/** 上次轮询时间(毫秒)。 */
|
|
89
|
+
lastRunAt?: number
|
|
90
|
+
/** 下次总结时刻(毫秒)。 */
|
|
91
|
+
nextSummaryAt?: number
|
|
92
|
+
/** 上次轮询的结果。 */
|
|
93
|
+
lastResult?: string
|
|
94
|
+
}
|
|
95
|
+
/** 工具策略。 */
|
|
96
|
+
policy: {
|
|
97
|
+
/** 默认配置档。 */
|
|
98
|
+
defaultProfile: string
|
|
99
|
+
/** 配置档名字。 */
|
|
100
|
+
profiles: string[]
|
|
101
|
+
/** 按聊天指定的配置档。 */
|
|
102
|
+
chats: Record<string, string>
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** 会话表的一行。 */
|
|
107
|
+
interface SessionRow {
|
|
108
|
+
/** 聊天目标键,例如 `group:123`。 */
|
|
109
|
+
target: string
|
|
110
|
+
/** 绑定的上游会话。 */
|
|
111
|
+
sessionID?: string
|
|
112
|
+
/** 当前是否有一轮在跑。 */
|
|
113
|
+
busy: boolean
|
|
114
|
+
/** 缓存中的消息条数。 */
|
|
115
|
+
buffered: number
|
|
116
|
+
/** 是否在等待重试。 */
|
|
117
|
+
pending: boolean
|
|
118
|
+
/** 唤醒方式,来自会话覆盖。 */
|
|
119
|
+
wake?: string
|
|
120
|
+
/** 是否允许主动说话。 */
|
|
121
|
+
proactive?: boolean
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* 采集运行状态快照。
|
|
126
|
+
*
|
|
127
|
+
* @param runtime 运行时句柄;还没就绪的部分留空,不让面板因为缺一个模块就报错。
|
|
128
|
+
*/
|
|
129
|
+
export async function collectStatus(runtime: PanelRuntime): Promise<StatusSnapshot> {
|
|
130
|
+
const config = runtime.config
|
|
131
|
+
const sessions = await collectSessions(runtime)
|
|
132
|
+
const policy = await runtime.policy?.current()
|
|
133
|
+
const diary = runtime.diary
|
|
134
|
+
return {
|
|
135
|
+
version: runtime.version,
|
|
136
|
+
startedAt: runtime.startedAt,
|
|
137
|
+
uptimeMs: Date.now() - runtime.startedAt,
|
|
138
|
+
runtime: {
|
|
139
|
+
home: runtime.home.directory,
|
|
140
|
+
logDir: config.log.dir.trim() || defaultLogDir(),
|
|
141
|
+
...(runtime.agent ? { agent: runtime.agent } : {}),
|
|
142
|
+
...(config.model
|
|
143
|
+
? {
|
|
144
|
+
model: [config.model.providerID, config.model.id, config.model.variant]
|
|
145
|
+
.filter(Boolean)
|
|
146
|
+
.join("/"),
|
|
147
|
+
}
|
|
148
|
+
: {}),
|
|
149
|
+
panel: {
|
|
150
|
+
enabled: config.panel.enabled,
|
|
151
|
+
host: config.panel.host,
|
|
152
|
+
port: config.panel.port,
|
|
153
|
+
},
|
|
154
|
+
},
|
|
155
|
+
connection: {
|
|
156
|
+
connected: runtime.client?.connected ?? false,
|
|
157
|
+
...(runtime.client?.selfId ? { selfId: runtime.client.selfId } : {}),
|
|
158
|
+
reconnects: runtime.client?.reconnects ?? 0,
|
|
159
|
+
...(runtime.client?.lastReconnectAt
|
|
160
|
+
? { lastReconnectAt: runtime.client.lastReconnectAt }
|
|
161
|
+
: {}),
|
|
162
|
+
},
|
|
163
|
+
sessions,
|
|
164
|
+
rateLimit: runtime.limiter?.snapshot() ?? [],
|
|
165
|
+
traces: runtime.tracer?.spans().slice(-50) ?? [],
|
|
166
|
+
diary: {
|
|
167
|
+
enabled: config.diary.enabled,
|
|
168
|
+
summaryTime: config.diary.summaryTime,
|
|
169
|
+
...(diary?.nextRunAt() !== undefined ? { nextRunAt: diary.nextRunAt() } : {}),
|
|
170
|
+
...(diary?.lastRunAt() !== undefined ? { lastRunAt: diary.lastRunAt() } : {}),
|
|
171
|
+
...(diary ? { nextSummaryAt: diary.nextSummaryAt() } : {}),
|
|
172
|
+
...(diary?.lastResult() ? { lastResult: diary.lastResult() } : {}),
|
|
173
|
+
},
|
|
174
|
+
policy: {
|
|
175
|
+
defaultProfile: policy?.defaultProfile ?? "chat",
|
|
176
|
+
profiles: policy ? Object.keys(policy.profiles) : [],
|
|
177
|
+
chats: policy?.chats ?? {},
|
|
178
|
+
},
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** 会话表:会话状态加上会话覆盖里的唤醒方式。 */
|
|
183
|
+
async function collectSessions(runtime: PanelRuntime): Promise<SessionRow[]> {
|
|
184
|
+
const manager = runtime.manager
|
|
185
|
+
if (!manager) return []
|
|
186
|
+
const items = manager.snapshot()
|
|
187
|
+
const result: SessionRow[] = []
|
|
188
|
+
for (const item of items) {
|
|
189
|
+
const override = await runtime.overrides?.for(item.target)
|
|
190
|
+
result.push({
|
|
191
|
+
target: targetKey(item.target),
|
|
192
|
+
...(item.sessionID ? { sessionID: item.sessionID } : {}),
|
|
193
|
+
busy: item.busy,
|
|
194
|
+
buffered: item.buffered,
|
|
195
|
+
pending: item.pending,
|
|
196
|
+
...(override?.wake ? { wake: override.wake } : {}),
|
|
197
|
+
...(override?.proactive !== undefined ? { proactive: override.proactive } : {}),
|
|
198
|
+
})
|
|
199
|
+
}
|
|
200
|
+
return result
|
|
201
|
+
}
|
package/src/rate-limit.ts
CHANGED
|
@@ -135,6 +135,52 @@ export class SendRateLimiter {
|
|
|
135
135
|
return Math.min(minuteLeft, hourLeft)
|
|
136
136
|
}
|
|
137
137
|
|
|
138
|
+
/** 各目标的用量快照,供状态面板展示。 */
|
|
139
|
+
snapshot(): Array<{
|
|
140
|
+
scope: string
|
|
141
|
+
maxPerMinute: number
|
|
142
|
+
maxPerHour: number
|
|
143
|
+
usedPerMinute: number
|
|
144
|
+
usedPerHour: number
|
|
145
|
+
minuteLeft: number
|
|
146
|
+
hourLeft: number
|
|
147
|
+
}> {
|
|
148
|
+
const now = this.currentTime
|
|
149
|
+
const scopes = new Set<string>([...this.records.keys(), ...this.locks.keys()])
|
|
150
|
+
const result: Array<{
|
|
151
|
+
scope: string
|
|
152
|
+
maxPerMinute: number
|
|
153
|
+
maxPerHour: number
|
|
154
|
+
usedPerMinute: number
|
|
155
|
+
usedPerHour: number
|
|
156
|
+
minuteLeft: number
|
|
157
|
+
hourLeft: number
|
|
158
|
+
}> = []
|
|
159
|
+
for (const scope of [...scopes].sort()) {
|
|
160
|
+
const records = this.recent(scope, now)
|
|
161
|
+
const usedPerMinute = records.filter((record) => now - record.at < MINUTE_MS).length
|
|
162
|
+
const usedPerHour = records.length
|
|
163
|
+
const minuteLeft =
|
|
164
|
+
this.config.maxPerMinute > 0
|
|
165
|
+
? Math.max(0, this.config.maxPerMinute - usedPerMinute)
|
|
166
|
+
: Number.POSITIVE_INFINITY
|
|
167
|
+
const hourLeft =
|
|
168
|
+
this.config.maxPerHour > 0
|
|
169
|
+
? Math.max(0, this.config.maxPerHour - usedPerHour)
|
|
170
|
+
: Number.POSITIVE_INFINITY
|
|
171
|
+
result.push({
|
|
172
|
+
scope,
|
|
173
|
+
maxPerMinute: this.config.maxPerMinute,
|
|
174
|
+
maxPerHour: this.config.maxPerHour,
|
|
175
|
+
usedPerMinute,
|
|
176
|
+
usedPerHour,
|
|
177
|
+
minuteLeft,
|
|
178
|
+
hourLeft,
|
|
179
|
+
})
|
|
180
|
+
}
|
|
181
|
+
return result
|
|
182
|
+
}
|
|
183
|
+
|
|
138
184
|
/** 判定并记账一次发送。 */
|
|
139
185
|
private async admit(
|
|
140
186
|
scope: string,
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { unrefTimer } from "../async"
|
|
2
|
+
|
|
3
|
+
export interface ClaimTimerOptions {
|
|
4
|
+
/** 重试间隔。 */
|
|
5
|
+
intervalMs: number
|
|
6
|
+
/** 现在要不要试:已经拿到锁就不必再试。 */
|
|
7
|
+
shouldTry: () => boolean
|
|
8
|
+
/** 尝试抢占机器锁;返回 true 表示抢到了。 */
|
|
9
|
+
claim: () => Promise<boolean>
|
|
10
|
+
/** 抢到锁之后搭运行时。 */
|
|
11
|
+
onClaimed: () => Promise<void>
|
|
12
|
+
/** 出错时的处理。 */
|
|
13
|
+
onError: (error: unknown) => void
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* 启动接管重试定时器。
|
|
18
|
+
*
|
|
19
|
+
* 装上它就意味着后面还有重试的机会:首次初始化失败时靠它再搭一次,
|
|
20
|
+
* 所以它必须先于第一次抢锁装好。
|
|
21
|
+
*/
|
|
22
|
+
export function startClaimTimer(options: ClaimTimerOptions): { stop: () => void } {
|
|
23
|
+
const timer = setInterval(() => {
|
|
24
|
+
if (!options.shouldTry()) return
|
|
25
|
+
void options
|
|
26
|
+
.claim()
|
|
27
|
+
.then(async (ok) => {
|
|
28
|
+
if (!ok) return
|
|
29
|
+
await options.onClaimed()
|
|
30
|
+
})
|
|
31
|
+
.catch((error: unknown) => options.onError(error))
|
|
32
|
+
}, options.intervalMs)
|
|
33
|
+
unrefTimer(timer)
|
|
34
|
+
return {
|
|
35
|
+
stop: () => clearInterval(timer),
|
|
36
|
+
}
|
|
37
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 运行时启动状态机。
|
|
3
|
+
*
|
|
4
|
+
* 只有全部步骤成功才算启动完成:中途失败时下一次接管会重新搭一遍,
|
|
5
|
+
* 而且失败必须把机器锁放掉,否则别的实例永远接不了手。
|
|
6
|
+
*/
|
|
7
|
+
export class RuntimeStart {
|
|
8
|
+
private started = false
|
|
9
|
+
private starting: Promise<void> | undefined
|
|
10
|
+
|
|
11
|
+
constructor(
|
|
12
|
+
private readonly options: {
|
|
13
|
+
/** 能不能启动:卸载已经开始时返回 false。 */
|
|
14
|
+
canStart: () => boolean
|
|
15
|
+
/** 搭建运行时:工具、钩子与 NapCat 连接都在这一步。 */
|
|
16
|
+
setup: () => Promise<void>
|
|
17
|
+
/** 启动失败时的补救:释放机器锁。 */
|
|
18
|
+
onFailure: (error: unknown) => Promise<void> | void
|
|
19
|
+
},
|
|
20
|
+
) {}
|
|
21
|
+
|
|
22
|
+
/** 已经启动完成。 */
|
|
23
|
+
get isStarted(): boolean {
|
|
24
|
+
return this.started
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** 正在启动中。 */
|
|
28
|
+
get isStarting(): boolean {
|
|
29
|
+
return this.starting !== undefined
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* 启动运行时。
|
|
34
|
+
*
|
|
35
|
+
* 并发调用共享同一次启动;失败时把错误原样抛出去,由调用方决定是重试还是退出。
|
|
36
|
+
*/
|
|
37
|
+
async run(): Promise<void> {
|
|
38
|
+
if (this.started) return
|
|
39
|
+
if (this.starting) return this.starting
|
|
40
|
+
if (!this.options.canStart()) return
|
|
41
|
+
this.starting = (async () => {
|
|
42
|
+
try {
|
|
43
|
+
await this.options.setup()
|
|
44
|
+
this.started = true
|
|
45
|
+
} catch (error) {
|
|
46
|
+
// 启动失败还占着锁的话,别的实例永远接不了手;先补救再往上抛。
|
|
47
|
+
await this.options.onFailure(error)
|
|
48
|
+
throw error
|
|
49
|
+
}
|
|
50
|
+
})().finally(() => {
|
|
51
|
+
this.starting = undefined
|
|
52
|
+
})
|
|
53
|
+
return this.starting
|
|
54
|
+
}
|
|
55
|
+
}
|
package/src/sensitive.ts
CHANGED
|
@@ -278,7 +278,7 @@ export interface SensitiveCheckerOptions {
|
|
|
278
278
|
* 命中就整条拦截:出站消息要么原样发出去,要么不发。
|
|
279
279
|
*/
|
|
280
280
|
export class SensitiveChecker {
|
|
281
|
-
private
|
|
281
|
+
private enabled: boolean
|
|
282
282
|
private readonly knownSecrets: string[]
|
|
283
283
|
private readonly custom: Detector[]
|
|
284
284
|
private readonly only: string[]
|
|
@@ -293,6 +293,11 @@ export class SensitiveChecker {
|
|
|
293
293
|
this.only = [...SECRET_DETECTORS, ...this.custom.map((detector) => detector.id)]
|
|
294
294
|
}
|
|
295
295
|
|
|
296
|
+
/** 打开或关闭检查:开关是热字段,改完立即生效。 */
|
|
297
|
+
setEnabled(enabled: boolean): void {
|
|
298
|
+
this.enabled = enabled
|
|
299
|
+
}
|
|
300
|
+
|
|
296
301
|
/**
|
|
297
302
|
* 检查一段即将发出的内容。
|
|
298
303
|
*
|
package/src/session/find.ts
CHANGED
|
@@ -2,44 +2,78 @@ import type { Plugin } from "@opencode/plugin"
|
|
|
2
2
|
import type { Logger } from "../logger"
|
|
3
3
|
|
|
4
4
|
/** 会话列表最多翻几页。 */
|
|
5
|
-
const MAX_PAGES =
|
|
5
|
+
const MAX_PAGES = 20
|
|
6
6
|
/** 每页抓多少条。 */
|
|
7
|
-
const PAGE_SIZE =
|
|
7
|
+
const PAGE_SIZE = 200
|
|
8
8
|
|
|
9
9
|
type ListResult = Awaited<ReturnType<Plugin.Context["session"]["list"]>>
|
|
10
10
|
/** 会话列表里的单条会话。 */
|
|
11
11
|
export type ListedSession = ListResult["data"][number]
|
|
12
12
|
|
|
13
|
+
/** 查找会话时的可调项。 */
|
|
14
|
+
export interface FindOptions {
|
|
15
|
+
/** 最多返回多少个命中的会话。 */
|
|
16
|
+
limit?: number
|
|
17
|
+
/** 最多翻几页。 */
|
|
18
|
+
maxPages?: number
|
|
19
|
+
/** 每页抓多少条。 */
|
|
20
|
+
pageSize?: number
|
|
21
|
+
}
|
|
22
|
+
|
|
13
23
|
/**
|
|
14
24
|
* 在指定目录下按谓词查找会话。
|
|
15
25
|
*
|
|
16
26
|
* 列表按创建时间倒序、翻页上限固定,避免会话很多时把整个列表拉一遍。
|
|
17
27
|
*
|
|
18
|
-
* @returns
|
|
28
|
+
* @returns 命中的会话;找不到或查询失败时返回空数组。
|
|
19
29
|
*/
|
|
20
|
-
export async function
|
|
30
|
+
export async function findSessions(
|
|
21
31
|
ctx: Plugin.Context,
|
|
22
32
|
directory: NonNullable<Parameters<Plugin.Context["session"]["list"]>[0]>["directory"],
|
|
23
33
|
match: (session: ListedSession) => boolean,
|
|
24
34
|
logger: Logger,
|
|
25
35
|
failure: string,
|
|
26
|
-
|
|
36
|
+
options: FindOptions = {},
|
|
37
|
+
): Promise<ListedSession[]> {
|
|
38
|
+
const limit = options.limit ?? 1
|
|
39
|
+
const maxPages = options.maxPages ?? MAX_PAGES
|
|
40
|
+
const pageSize = options.pageSize ?? PAGE_SIZE
|
|
41
|
+
const found: ListedSession[] = []
|
|
27
42
|
let cursor: ListResult["cursor"]["next"] | undefined
|
|
28
43
|
try {
|
|
29
|
-
for (let page = 0; page <
|
|
44
|
+
for (let page = 0; page < maxPages && found.length < limit; page += 1) {
|
|
30
45
|
const result = await ctx.session.list({
|
|
31
46
|
directory,
|
|
32
|
-
limit:
|
|
47
|
+
limit: pageSize,
|
|
33
48
|
order: "desc",
|
|
34
49
|
...(cursor ? { cursor } : {}),
|
|
35
50
|
})
|
|
36
|
-
const
|
|
37
|
-
|
|
51
|
+
for (const session of result.data) {
|
|
52
|
+
if (!match(session)) continue
|
|
53
|
+
found.push(session)
|
|
54
|
+
if (found.length >= limit) break
|
|
55
|
+
}
|
|
38
56
|
cursor = result.cursor.next ?? undefined
|
|
39
57
|
if (!cursor) break
|
|
40
58
|
}
|
|
41
59
|
} catch (error) {
|
|
42
60
|
logger.warn(failure, error)
|
|
43
61
|
}
|
|
44
|
-
return
|
|
62
|
+
return found
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* 在指定目录下按谓词查找第一个会话。
|
|
67
|
+
*
|
|
68
|
+
* @returns 命中的会话 ID;找不到或查询失败时返回 `undefined`。
|
|
69
|
+
*/
|
|
70
|
+
export async function findSession(
|
|
71
|
+
ctx: Plugin.Context,
|
|
72
|
+
directory: NonNullable<Parameters<Plugin.Context["session"]["list"]>[0]>["directory"],
|
|
73
|
+
match: (session: ListedSession) => boolean,
|
|
74
|
+
logger: Logger,
|
|
75
|
+
failure: string,
|
|
76
|
+
): Promise<string | undefined> {
|
|
77
|
+
const [first] = await findSessions(ctx, directory, match, logger, failure, { limit: 1 })
|
|
78
|
+
return first?.id
|
|
45
79
|
}
|