@cmach_socket/opencode-qq-bot 0.3.4 → 0.6.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 +69 -0
- package/README.md +370 -44
- package/package.json +21 -2
- package/src/access.ts +79 -0
- package/src/bot-lock.ts +17 -26
- package/src/chat.ts +0 -20
- package/src/commands.ts +267 -0
- package/src/config.ts +602 -48
- package/src/emoji/command.ts +184 -0
- package/src/emoji/faces.ts +136 -0
- package/src/emoji/favorite-index.ts +150 -0
- package/src/emoji/favorites.ts +161 -0
- package/src/emoji/label.ts +318 -0
- package/src/events/notice.ts +139 -0
- package/src/events/store.ts +53 -0
- package/src/home.ts +45 -0
- package/src/index.ts +437 -63
- package/src/instance.ts +30 -17
- package/src/keepalive.ts +222 -0
- package/src/logger.ts +273 -17
- package/src/media-path.ts +186 -0
- package/src/model-view.ts +136 -0
- package/src/naplink/client.ts +14 -17
- package/src/naplink/history.ts +263 -0
- package/src/naplink/media.ts +34 -103
- package/src/naplink/render.ts +142 -33
- package/src/outbound.ts +174 -0
- package/src/overrides.ts +312 -0
- package/src/rate-limit.ts +228 -0
- package/src/safe-fetch.ts +143 -0
- package/src/sensitive.ts +309 -0
- package/src/session/manager.ts +488 -31
- package/src/session/proactive.ts +21 -0
- package/src/session/prompt.ts +4 -1
- package/src/session/soul.ts +46 -0
- package/src/tools/ask-guard.ts +5 -5
- package/src/tools/policy-guard.ts +45 -0
- package/src/tools/policy.ts +205 -0
- package/src/tools/qq.ts +353 -41
- package/src/tools/send-guard.ts +73 -0
- package/src/trace.ts +209 -0
- package/src/tui-commands.ts +70 -0
- package/src/version.ts +12 -0
package/src/trace.ts
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto"
|
|
2
|
+
import { appendFile, mkdir, readdir, stat, unlink } from "node:fs/promises"
|
|
3
|
+
import { join } from "node:path"
|
|
4
|
+
import type { Logger } from "./logger"
|
|
5
|
+
|
|
6
|
+
/** 一次调用链里的关键节点。 */
|
|
7
|
+
export type TraceEventName = "event_received" | "agent_start" | "handler_start" | "response_sent"
|
|
8
|
+
|
|
9
|
+
/** 一条追踪记录。 */
|
|
10
|
+
export interface TraceSpan {
|
|
11
|
+
/** 一次入站消息的追踪 id。 */
|
|
12
|
+
traceId: string
|
|
13
|
+
/** 节点自己的 id。 */
|
|
14
|
+
spanId: string
|
|
15
|
+
/** 节点名。 */
|
|
16
|
+
name: TraceEventName
|
|
17
|
+
/** 发生时间(毫秒)。 */
|
|
18
|
+
at: number
|
|
19
|
+
/** 聊天目标。 */
|
|
20
|
+
target?: string
|
|
21
|
+
/** 附加信息:只放元数据,不放消息正文。 */
|
|
22
|
+
attributes?: Record<string, unknown>
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** 追踪器选项。 */
|
|
26
|
+
export interface TracerOptions {
|
|
27
|
+
/** 是否记录追踪。 */
|
|
28
|
+
enabled?: boolean
|
|
29
|
+
/** 追踪文件目录,空表示由调用方给出默认目录。 */
|
|
30
|
+
dir?: string
|
|
31
|
+
/** 追踪文件总容量上限(MB)。 */
|
|
32
|
+
maxSizeMb?: number
|
|
33
|
+
/** 追踪文件保留天数。 */
|
|
34
|
+
retentionDays?: number
|
|
35
|
+
/** 内存里保留多少条记录。 */
|
|
36
|
+
memorySpans?: number
|
|
37
|
+
/** 取当前时间(毫秒),测试时可注入。 */
|
|
38
|
+
now?: () => number
|
|
39
|
+
/** 生成 id,测试时可注入。 */
|
|
40
|
+
id?: () => string
|
|
41
|
+
/** 日志器:写文件失败时告警。 */
|
|
42
|
+
logger?: Logger
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** 追踪文件名前缀。 */
|
|
46
|
+
const FILE_PREFIX = "qq-bot-traces-"
|
|
47
|
+
/** 追踪文件后缀。 */
|
|
48
|
+
const FILE_SUFFIX = ".jsonl"
|
|
49
|
+
/** 内存里保留的记录条数上限。 */
|
|
50
|
+
const DEFAULT_MEMORY_SPANS = 1000
|
|
51
|
+
/** 容量上限的默认值(MB)。 */
|
|
52
|
+
const DEFAULT_MAX_SIZE_MB = 80
|
|
53
|
+
/** 保留天数的默认值。 */
|
|
54
|
+
const DEFAULT_RETENTION_DAYS = 7
|
|
55
|
+
|
|
56
|
+
interface TraceFile {
|
|
57
|
+
/** 文件完整路径。 */
|
|
58
|
+
path: string
|
|
59
|
+
/** 文件大小(字节)。 */
|
|
60
|
+
size: number
|
|
61
|
+
/** 最后修改时间(毫秒)。 */
|
|
62
|
+
mtime: number
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* 调用链追踪。
|
|
67
|
+
*
|
|
68
|
+
* 一条入站消息拿一个 trace_id,事件接收、模型起跑、模型处理、出站回复
|
|
69
|
+
* 各自记一个节点,事后按 trace_id 就能把这一轮串起来。
|
|
70
|
+
*
|
|
71
|
+
* 记录只存元数据(目标、消息号、字数),不存消息正文;文件按天写 JSONL,
|
|
72
|
+
* 总容量与保留天数都有上限,超了先删旧文件。
|
|
73
|
+
*/
|
|
74
|
+
export class Tracer {
|
|
75
|
+
private readonly enabled: boolean
|
|
76
|
+
private readonly dir: string
|
|
77
|
+
private readonly maxBytes: number
|
|
78
|
+
private readonly retentionMs: number
|
|
79
|
+
private readonly memoryLimit: number
|
|
80
|
+
private readonly currentTime: () => number
|
|
81
|
+
private readonly nextId: () => string
|
|
82
|
+
private readonly logger: Logger | undefined
|
|
83
|
+
/** 内存里的最近记录。 */
|
|
84
|
+
private readonly memory: TraceSpan[] = []
|
|
85
|
+
/** 追踪目录当前占用的字节数。 */
|
|
86
|
+
private bytes = 0
|
|
87
|
+
|
|
88
|
+
constructor(private readonly options: TracerOptions = {}) {
|
|
89
|
+
this.enabled = options.enabled ?? true
|
|
90
|
+
this.dir = options.dir ?? ""
|
|
91
|
+
this.maxBytes = Math.max(1, options.maxSizeMb ?? DEFAULT_MAX_SIZE_MB) * 1024 * 1024
|
|
92
|
+
this.retentionMs =
|
|
93
|
+
Math.max(1, options.retentionDays ?? DEFAULT_RETENTION_DAYS) * 24 * 3600 * 1000
|
|
94
|
+
this.memoryLimit = Math.max(1, options.memorySpans ?? DEFAULT_MEMORY_SPANS)
|
|
95
|
+
this.currentTime = options.now ?? Date.now
|
|
96
|
+
this.nextId = options.id ?? (() => randomUUID())
|
|
97
|
+
this.logger = options.logger
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** 是否在记录。 */
|
|
101
|
+
get active(): boolean {
|
|
102
|
+
return this.enabled && this.dir.length > 0
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** 开一条新的追踪,返回 trace id。 */
|
|
106
|
+
startTrace(): string {
|
|
107
|
+
return this.nextId()
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** 记一个节点。 */
|
|
111
|
+
async record(
|
|
112
|
+
name: TraceEventName,
|
|
113
|
+
traceId: string,
|
|
114
|
+
attributes?: Record<string, unknown>,
|
|
115
|
+
target?: string,
|
|
116
|
+
): Promise<void> {
|
|
117
|
+
if (!this.active) return
|
|
118
|
+
const span: TraceSpan = {
|
|
119
|
+
traceId,
|
|
120
|
+
spanId: this.nextId(),
|
|
121
|
+
name,
|
|
122
|
+
at: this.currentTime(),
|
|
123
|
+
...(target ? { target } : {}),
|
|
124
|
+
...(attributes && Object.keys(attributes).length > 0 ? { attributes } : {}),
|
|
125
|
+
}
|
|
126
|
+
this.memory.push(span)
|
|
127
|
+
while (this.memory.length > this.memoryLimit) this.memory.shift()
|
|
128
|
+
const line = `${JSON.stringify(span)}\n`
|
|
129
|
+
try {
|
|
130
|
+
if (!(await this.ensureRoom())) return
|
|
131
|
+
await this.write(line)
|
|
132
|
+
} catch (error) {
|
|
133
|
+
this.logger?.warn("写入调用链追踪失败", error)
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** 内存里保留的最近记录。 */
|
|
138
|
+
spans(): TraceSpan[] {
|
|
139
|
+
return [...this.memory]
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* 清理追踪文件。
|
|
144
|
+
*
|
|
145
|
+
* 超过保留天数的文件直接删;总容量超了再从旧文件开始删。
|
|
146
|
+
*/
|
|
147
|
+
async prune(): Promise<void> {
|
|
148
|
+
if (!this.active) return
|
|
149
|
+
const now = this.currentTime()
|
|
150
|
+
const files = await this.listFiles()
|
|
151
|
+
const kept: TraceFile[] = []
|
|
152
|
+
for (const file of files) {
|
|
153
|
+
if (now - file.mtime > this.retentionMs) {
|
|
154
|
+
await unlink(file.path).catch(() => undefined)
|
|
155
|
+
continue
|
|
156
|
+
}
|
|
157
|
+
kept.push(file)
|
|
158
|
+
}
|
|
159
|
+
let total = kept.reduce((sum, file) => sum + file.size, 0)
|
|
160
|
+
if (total > this.maxBytes) {
|
|
161
|
+
const sorted = [...kept].sort((left, right) => left.mtime - right.mtime)
|
|
162
|
+
for (const file of sorted) {
|
|
163
|
+
if (total <= this.maxBytes * 0.9) break
|
|
164
|
+
const removed = await unlink(file.path).then(
|
|
165
|
+
() => true,
|
|
166
|
+
() => false,
|
|
167
|
+
)
|
|
168
|
+
if (removed) total -= file.size
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
this.bytes = total
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** 追踪目录里的文件。 */
|
|
175
|
+
private async listFiles(): Promise<TraceFile[]> {
|
|
176
|
+
const entries = await readdir(this.dir).catch(() => [] as string[])
|
|
177
|
+
const files: TraceFile[] = []
|
|
178
|
+
for (const name of entries) {
|
|
179
|
+
if (!name.startsWith(FILE_PREFIX) || !name.endsWith(FILE_SUFFIX)) continue
|
|
180
|
+
const path = join(this.dir, name)
|
|
181
|
+
const info = await stat(path).catch(() => undefined)
|
|
182
|
+
if (!info?.isFile()) continue
|
|
183
|
+
files.push({ path, size: info.size, mtime: info.mtimeMs })
|
|
184
|
+
}
|
|
185
|
+
return files
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** 容量不够时先清旧文件;腾不出空间则返回 false。 */
|
|
189
|
+
private async ensureRoom(): Promise<boolean> {
|
|
190
|
+
if (this.bytes < this.maxBytes) return true
|
|
191
|
+
await this.prune()
|
|
192
|
+
if (this.bytes < this.maxBytes) return true
|
|
193
|
+
this.logger?.warn("调用链追踪已写满,丢弃新的追踪记录")
|
|
194
|
+
return false
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** 追加一行到当天的追踪文件。 */
|
|
198
|
+
private async write(line: string): Promise<void> {
|
|
199
|
+
await mkdir(this.dir, { recursive: true, mode: 0o700 }).catch(() => undefined)
|
|
200
|
+
const path = join(this.dir, `${FILE_PREFIX}${this.day()}${FILE_SUFFIX}`)
|
|
201
|
+
await appendFile(path, line, { encoding: "utf8", mode: 0o600 })
|
|
202
|
+
this.bytes += Buffer.byteLength(line)
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** 当天的日期(UTC)。 */
|
|
206
|
+
private day(): string {
|
|
207
|
+
return new Date(this.currentTime()).toISOString().slice(0, 10)
|
|
208
|
+
}
|
|
209
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import type { Plugin } from "@opencode/plugin"
|
|
2
|
+
import { type CommandDefinition, commandTargetFor, splitArgs, tuiCommandName } from "./commands"
|
|
3
|
+
import type { QQBotConfig } from "./config"
|
|
4
|
+
import type { Logger } from "./logger"
|
|
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 { createPlainSender } from "./tools/qq"
|
|
11
|
+
|
|
12
|
+
export { TUI_COMMAND_PREFIX, tuiCommandName } from "./commands"
|
|
13
|
+
|
|
14
|
+
export interface TuiCommandDeps {
|
|
15
|
+
ctx: Plugin.Context
|
|
16
|
+
config: QQBotConfig
|
|
17
|
+
logger: Logger
|
|
18
|
+
manager: SessionManager
|
|
19
|
+
policy: ToolPolicy
|
|
20
|
+
/** 会话行为覆盖,命令要展示各聊天的唤醒方式。 */
|
|
21
|
+
overrides: ChatOverrides
|
|
22
|
+
client: QQClient
|
|
23
|
+
/** 命令结果同样走限流。 */
|
|
24
|
+
limiter: SendRateLimiter
|
|
25
|
+
/** QQ 与 TUI 共用的命令表。 */
|
|
26
|
+
commands: readonly CommandDefinition[]
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* 把命令表以 `qq-` 前缀注册成 TUI 命令,与 QQ 侧共用同一份实现。
|
|
31
|
+
*
|
|
32
|
+
* 结果发到会话绑定的 QQ 聊天;没有绑定就发第一个配置目标。
|
|
33
|
+
*/
|
|
34
|
+
export async function registerTuiCommands(
|
|
35
|
+
deps: TuiCommandDeps,
|
|
36
|
+
): Promise<{ dispose(): Promise<void> }> {
|
|
37
|
+
const { ctx, config, logger, manager, policy, overrides, client, limiter, commands } = deps
|
|
38
|
+
|
|
39
|
+
const toolNames = async () => (await ctx.tool.list()).map((tool) => tool.id)
|
|
40
|
+
|
|
41
|
+
const send = createPlainSender(client, {
|
|
42
|
+
delayMs: config.sendDelayMs,
|
|
43
|
+
limiter,
|
|
44
|
+
logger,
|
|
45
|
+
failure: () => "发送 TUI 命令结果失败",
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
return await ctx.command.transform((editor) => {
|
|
49
|
+
for (const command of commands) {
|
|
50
|
+
const name = tuiCommandName(command.name)
|
|
51
|
+
editor.add({
|
|
52
|
+
name,
|
|
53
|
+
description: command.description,
|
|
54
|
+
execute: async (input) => {
|
|
55
|
+
const target = commandTargetFor(config, manager, input.sessionID)
|
|
56
|
+
if (!target) {
|
|
57
|
+
logger.warn(`没有可用的 QQ 目标,无法执行 /${name}`)
|
|
58
|
+
return
|
|
59
|
+
}
|
|
60
|
+
const args = splitArgs(input.prompt.text ?? "", name)
|
|
61
|
+
const body = await command.run(
|
|
62
|
+
{ config, manager, policy, overrides, target, toolNames, commands },
|
|
63
|
+
args,
|
|
64
|
+
)
|
|
65
|
+
if (body !== undefined) await send(target, body)
|
|
66
|
+
},
|
|
67
|
+
})
|
|
68
|
+
}
|
|
69
|
+
})
|
|
70
|
+
}
|
package/src/version.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs"
|
|
2
|
+
|
|
3
|
+
/** 读取 package.json 里的插件版本号;读取失败时返回 `unknown`。 */
|
|
4
|
+
export function pluginVersion(): string {
|
|
5
|
+
try {
|
|
6
|
+
const text = readFileSync(new URL("../package.json", import.meta.url), "utf8")
|
|
7
|
+
const pkg = JSON.parse(text) as { version?: unknown }
|
|
8
|
+
return typeof pkg.version === "string" && pkg.version ? pkg.version : "unknown"
|
|
9
|
+
} catch {
|
|
10
|
+
return "unknown"
|
|
11
|
+
}
|
|
12
|
+
}
|