@cmach_socket/opencode-qq-bot 0.5.1 → 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.
@@ -0,0 +1,205 @@
1
+ import { readFile, stat } from "node:fs/promises"
2
+ import { join } from "node:path"
3
+ import type { QQBotConfig } from "../config"
4
+ import type { Logger } from "../logger"
5
+
6
+ /** 消息发送者的角色,决定用哪一档工具配置。 */
7
+ export type Role = "owner" | "admin" | "member"
8
+
9
+ /** 发送者角色:owner 最高,其次 admin,其余按普通成员处理。 */
10
+ export function roleOf(config: QQBotConfig, senderQQ: string): Role {
11
+ const id = Number(senderQQ)
12
+ if (config.ownerQQ !== undefined && id === config.ownerQQ) return "owner"
13
+ if (config.admins.includes(id)) return "admin"
14
+ return "member"
15
+ }
16
+
17
+ /** 一档工具配置:allow 命中且 deny 不命中的工具才放行。 */
18
+ export interface ToolProfile {
19
+ allow: string[]
20
+ deny: string[]
21
+ }
22
+
23
+ /** `tool-profiles.json` 的结构。 */
24
+ export interface ToolPolicyFile {
25
+ /** 没有按聊天指定的配置时用哪一档。 */
26
+ defaultProfile: string
27
+ /** 配置档:名字 → 允许 / 禁止的工具。 */
28
+ profiles: Record<string, ToolProfile>
29
+ /** 按聊天指定的配置档:`group:100` / `private:200` → 档名。 */
30
+ chats: Record<string, string>
31
+ }
32
+
33
+ /** 内置默认值:普通聊天只留联网搜索、网页抓取和发消息工具,管理档全开。 */
34
+ export function defaultToolPolicy(): ToolPolicyFile {
35
+ return {
36
+ defaultProfile: "chat",
37
+ profiles: {
38
+ chat: { allow: ["websearch", "webfetch", "qq_*"], deny: [] },
39
+ readonly: { allow: ["read", "glob", "grep", "qq_*"], deny: [] },
40
+ admin: { allow: ["*"], deny: [] },
41
+ },
42
+ chats: {},
43
+ }
44
+ }
45
+
46
+ /** 默认的配置文件位置:当前工作目录下的 `tool-profiles.json`。 */
47
+ export function defaultToolProfilesPath(): string {
48
+ return join(process.cwd(), "tool-profiles.json")
49
+ }
50
+
51
+ /**
52
+ * 判断工具名是否命中通配模式。
53
+ *
54
+ * 只支持 `*`(任意长度)和 `?`(单个字符),大小写敏感,必须整名匹配。
55
+ */
56
+ export function globMatch(pattern: string, name: string): boolean {
57
+ const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&")
58
+ const source = escaped.replace(/\*/g, ".*").replace(/\?/g, ".")
59
+ return new RegExp(`^${source}$`).test(name)
60
+ }
61
+
62
+ function readNames(value: unknown, warn: (message: string) => void, where: string): string[] {
63
+ if (value === undefined) return []
64
+ if (!Array.isArray(value)) {
65
+ warn(`${where} 必须是字符串数组`)
66
+ return []
67
+ }
68
+ const names: string[] = []
69
+ for (const entry of value) {
70
+ if (typeof entry !== "string") {
71
+ warn(`${where} 里有非字符串项:${String(entry)}`)
72
+ continue
73
+ }
74
+ const name = entry.trim()
75
+ if (!name || names.includes(name)) continue
76
+ names.push(name)
77
+ }
78
+ return names
79
+ }
80
+
81
+ /**
82
+ * 解析并校验配置内容。
83
+ *
84
+ * 解析失败不抛错:回退到内置默认值并告警,避免一个手写的逗号让机器人失去工具。
85
+ */
86
+ export function parseToolPolicy(value: unknown, warn: (message: string) => void): ToolPolicyFile {
87
+ const fallback = defaultToolPolicy()
88
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
89
+ warn("工具配置必须是对象,已回退到内置默认值")
90
+ return fallback
91
+ }
92
+ const raw = value as Record<string, unknown>
93
+ const profiles: Record<string, ToolProfile> = {}
94
+ const source = raw.profiles
95
+ if (source !== undefined) {
96
+ if (!source || typeof source !== "object" || Array.isArray(source)) {
97
+ warn("profiles 必须是对象,已回退到内置默认值")
98
+ return fallback
99
+ }
100
+ for (const [name, entry] of Object.entries(source as Record<string, unknown>)) {
101
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
102
+ warn(`工具配置档 ${name} 必须是对象,已忽略`)
103
+ continue
104
+ }
105
+ const profile = entry as Record<string, unknown>
106
+ profiles[name] = {
107
+ allow: readNames(profile.allow, warn, `${name}.allow`),
108
+ deny: readNames(profile.deny, warn, `${name}.deny`),
109
+ }
110
+ }
111
+ }
112
+ // 用户没有覆盖的档沿用内置默认值,这样只写一档也能用。
113
+ for (const [name, profile] of Object.entries(fallback.profiles)) {
114
+ if (!profiles[name]) profiles[name] = profile
115
+ }
116
+ const defaultProfile =
117
+ typeof raw.defaultProfile === "string" && raw.defaultProfile.trim()
118
+ ? raw.defaultProfile.trim()
119
+ : fallback.defaultProfile
120
+ if (!profiles[defaultProfile]) {
121
+ warn(`defaultProfile 指向不存在的配置档 ${defaultProfile},已回退到 ${fallback.defaultProfile}`)
122
+ }
123
+ const chats: Record<string, string> = {}
124
+ if (raw.chats !== undefined) {
125
+ if (!raw.chats || typeof raw.chats !== "object" || Array.isArray(raw.chats)) {
126
+ warn("chats 必须是对象,已忽略")
127
+ } else {
128
+ for (const [key, name] of Object.entries(raw.chats as Record<string, unknown>)) {
129
+ if (typeof name !== "string" || !name.trim()) {
130
+ warn(`chats.${key} 必须是配置档名字,已忽略`)
131
+ continue
132
+ }
133
+ chats[key] = name.trim()
134
+ }
135
+ }
136
+ }
137
+ return {
138
+ defaultProfile: profiles[defaultProfile] ? defaultProfile : fallback.defaultProfile,
139
+ profiles,
140
+ chats,
141
+ }
142
+ }
143
+
144
+ /** 角色对应的配置档名字:owner 与 admin 用管理档,其他按聊天配置。 */
145
+ export function profileNameFor(file: ToolPolicyFile, role: Role, chatKey: string): string {
146
+ if (role !== "member") return file.profiles.admin ? "admin" : file.defaultProfile
147
+ const named = file.chats[chatKey]
148
+ if (named && file.profiles[named]) return named
149
+ return file.defaultProfile
150
+ }
151
+
152
+ /** 从工具名列表里筛出该配置档允许的项;deny 优先于 allow。 */
153
+ export function allowedTools(profile: ToolProfile, names: readonly string[]): string[] {
154
+ const allowed = (name: string) =>
155
+ !profile.deny.some((pattern) => globMatch(pattern, name)) &&
156
+ (profile.allow.includes("*") || profile.allow.some((pattern) => globMatch(pattern, name)))
157
+ return names.filter(allowed)
158
+ }
159
+
160
+ /** 工具配置的读取与热加载。 */
161
+ export class ToolPolicy {
162
+ private cached?: { mtime: number; file: ToolPolicyFile }
163
+
164
+ constructor(
165
+ private readonly path: string,
166
+ private readonly logger: Logger,
167
+ ) {}
168
+
169
+ /** 当前生效的配置;文件改动后按 mtime 重新读取。 */
170
+ async current(): Promise<ToolPolicyFile> {
171
+ const info = await stat(this.path).catch(() => undefined)
172
+ if (!info) {
173
+ if (!this.cached) this.cached = { mtime: 0, file: defaultToolPolicy() }
174
+ return this.cached.file
175
+ }
176
+ if (this.cached && this.cached.mtime === info.mtimeMs) return this.cached.file
177
+ try {
178
+ const text = await readFile(this.path, "utf8")
179
+ const file = parseToolPolicy(JSON.parse(text), (message) => {
180
+ this.logger.warn(`工具配置 ${this.path}:${message}`)
181
+ })
182
+ this.cached = { mtime: info.mtimeMs, file }
183
+ return file
184
+ } catch (error) {
185
+ // 半写或语法错误时保留上一份可用配置,等下一次写入后再加载。
186
+ this.logger.warn(`工具配置 ${this.path} 读取失败,继续沿用上一份配置`, error)
187
+ if (!this.cached) this.cached = { mtime: 0, file: defaultToolPolicy() }
188
+ return this.cached.file
189
+ }
190
+ }
191
+
192
+ /** 某个角色在某个聊天里能用的工具子集。 */
193
+ async allow(role: Role, chatKey: string, names: readonly string[]): Promise<Set<string>> {
194
+ const file = await this.current()
195
+ const profile = file.profiles[profileNameFor(file, role, chatKey)]
196
+ if (!profile) return new Set(names)
197
+ return new Set(allowedTools(profile, names))
198
+ }
199
+
200
+ /** 某个角色在某个聊天里生效的配置档名字,用于管理命令展示。 */
201
+ async profileOf(role: Role, chatKey: string): Promise<string> {
202
+ const file = await this.current()
203
+ return profileNameFor(file, role, chatKey)
204
+ }
205
+ }
package/src/tools/qq.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { Plugin } from "@opencode/plugin"
2
- import { type ChatTarget, isTargetEnabled, targetLabel } from "../chat"
2
+ import { isTargetAllowed } from "../access"
3
+ import { type ChatTarget, targetKey, targetLabel } from "../chat"
3
4
  import type { QQBotConfig } from "../config"
4
5
  import {
5
6
  CUSTOM_FACE_SUB_TYPE,
@@ -11,11 +12,12 @@ import type { FavoriteIndex } from "../emoji/favorite-index"
11
12
  import type { Logger } from "../logger"
12
13
  import type { OutboundMedia } from "../media-path"
13
14
  import type { QQClient } from "../naplink/client"
14
- import { splitGraphemes, splitMessage, toPlainText } from "../outbound"
15
+ import { splitGraphemes, splitMessage, segmentDelayMs, toPlainText } from "../outbound"
15
16
  import type { RateLimitVerdict, SendRateLimiter } from "../rate-limit"
16
17
  import { modelSendScope, pluginSendScope } from "../rate-limit"
17
18
  import type { SensitiveChecker } from "../sensitive"
18
19
  import type { SessionManager } from "../session/manager"
20
+ import type { Tracer } from "../trace"
19
21
 
20
22
  /** 工具命名空间,最终工具名为 qq_send_message 等。 */
21
23
  export const TOOL_NAMESPACE = "qq"
@@ -36,6 +38,8 @@ export interface ToolDeps {
36
38
  sensitive: SensitiveChecker
37
39
  /** 出站媒体的路径与地址把关。 */
38
40
  outbound: OutboundMedia
41
+ /** 调用链追踪器;不传就不记追踪。 */
42
+ tracer?: Tracer
39
43
  }
40
44
 
41
45
  interface SendMessageInput {
@@ -74,6 +78,9 @@ interface MessageIdInput {
74
78
  /** QQ 单条消息的保守长度上限,超过时按段发送。 */
75
79
  export { MAX_MESSAGE_CHARS } from "../outbound"
76
80
 
81
+ /** 合并转发里单个节点的字数上限,留出余量避免被 NapCat 截断。 */
82
+ const FORWARD_NODE_CHARS = 3000
83
+
77
84
  function text(value: string, metadata?: Record<string, unknown>) {
78
85
  // 工具返回 error 文本时状态仍是 completed;把失败标记带给发送守卫。
79
86
  const marks = { ...(value.startsWith("error:") ? { failed: true } : {}), ...metadata }
@@ -127,6 +134,36 @@ export async function sendPlainMessage(
127
134
  return sent
128
135
  }
129
136
 
137
+ /** 命令结果发送通道的配置。 */
138
+ export interface PlainSenderOptions {
139
+ delayMs?: number
140
+ limiter: SendRateLimiter
141
+ logger: Logger
142
+ /** 发送失败时写进日志的说明。 */
143
+ failure: (target: ChatTarget) => string
144
+ }
145
+
146
+ /**
147
+ * 创建命令结果的发送通道。
148
+ *
149
+ * 发送失败只记日志,不往上抛:命令已经执行完,不该因为回执失败再报错。
150
+ */
151
+ export function createPlainSender(
152
+ client: QQClient,
153
+ options: PlainSenderOptions,
154
+ ): (target: ChatTarget, content: string) => Promise<void> {
155
+ return async (target, content) => {
156
+ try {
157
+ await sendPlainMessage(client, target, content, {
158
+ delayMs: options.delayMs,
159
+ limiter: options.limiter,
160
+ })
161
+ } catch (error) {
162
+ options.logger.error(options.failure(target), error)
163
+ }
164
+ }
165
+ }
166
+
130
167
  /**
131
168
  * 注册 QQ 命名空间下的工具。
132
169
  *
@@ -145,13 +182,14 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
145
182
  limiter,
146
183
  sensitive,
147
184
  outbound,
185
+ tracer,
148
186
  } = deps
149
187
 
150
188
  const requireTarget = (sessionID: string): ChatTarget | undefined => {
151
189
  const target = manager.targetForSession(sessionID)
152
190
  if (!target) return undefined
153
- if (!isTargetEnabled(config, target)) {
154
- logger.warn(`${targetLabel(target)} 已不在配置中,拒绝工具调用`)
191
+ if (!isTargetAllowed(config.access, target, config.ownerQQ)) {
192
+ logger.warn(`${targetLabel(target)} 已不在放行名单里,拒绝工具调用`)
155
193
  return undefined
156
194
  }
157
195
  if (!manager.hasActiveTurn(sessionID)) {
@@ -165,6 +203,27 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
165
203
  let operationSeq = 0
166
204
  const nextOperation = (): string => `send-${++operationSeq}`
167
205
 
206
+ /** 当前轮次的追踪 id,用于把这次发送记进调用链。 */
207
+ const traceIdOf = (sessionID: string): string | undefined =>
208
+ manager.activeTurn(sessionID)?.turn.traceId
209
+
210
+ /** 日志里带上追踪 id,方便按一轮排查。 */
211
+ const traceMeta = (sessionID: string): Record<string, unknown> => {
212
+ const traceId = traceIdOf(sessionID)
213
+ return traceId ? { trace_id: traceId } : {}
214
+ }
215
+
216
+ /** 记一个“回复已发出”的追踪节点。 */
217
+ const traceSent = async (
218
+ sessionID: string,
219
+ target: ChatTarget,
220
+ attributes: Record<string, unknown>,
221
+ ): Promise<void> => {
222
+ const traceId = traceIdOf(sessionID)
223
+ if (!traceId) return
224
+ await tracer?.record("response_sent", traceId, attributes, targetKey(target))
225
+ }
226
+
168
227
  /**
169
228
  * 申请一次出站发送许可。
170
229
  *
@@ -222,6 +281,58 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
222
281
  ? client.api.sendGroupPoke(target.id, userId)
223
282
  : client.api.sendFriendPoke(userId)
224
283
 
284
+ // 合并转发时机器人自己的昵称,取一次就够。
285
+ let botName: string | undefined
286
+
287
+ /** 机器人在合并转发里的身份。 */
288
+ const botIdentity = async (): Promise<{ userId: number; nickname: string }> => {
289
+ if (!botName) {
290
+ const info = (await client.api.getLoginInfo().catch(() => undefined)) as
291
+ { nickname?: string } | undefined
292
+ botName = info?.nickname?.trim() || "机器人"
293
+ }
294
+ const userId = Number(client.selfId ?? 0)
295
+ return { userId: Number.isFinite(userId) ? userId : 0, nickname: botName }
296
+ }
297
+
298
+ /**
299
+ * 太长的回复改成合并转发发出去。
300
+ *
301
+ * 一口气刷十几条会把群刷爆,合并转发只占一条消息。
302
+ */
303
+ const sendAsForward = async (
304
+ sessionID: string,
305
+ target: ChatTarget,
306
+ plain: string,
307
+ operation: string,
308
+ length: number,
309
+ ) => {
310
+ const label = targetLabel(target)
311
+ const identity = await botIdentity()
312
+ const nodes = splitMessage(plain, FORWARD_NODE_CHARS).map((chunk) => ({
313
+ user_id: identity.userId,
314
+ nickname: identity.nickname,
315
+ content: [{ type: "text", data: { text: chunk } }],
316
+ }))
317
+ try {
318
+ const verdict = await permit(target, operation)
319
+ if (!verdict.allowed) return refuse(sessionID, verdict, 0, nodes.length)
320
+ const response = await sendForward(target, nodes)
321
+ const messageId = messageIdOf(response)
322
+ if (messageId) manager.rememberOutgoing(target, messageId)
323
+ manager.markMessageSent(sessionID)
324
+ logger.info(
325
+ `${label} 已发送 ${length} 字(合并转发 ${nodes.length} 个节点)`,
326
+ traceMeta(sessionID),
327
+ )
328
+ await traceSent(sessionID, target, { chars: length, mode: "forward", nodes: nodes.length })
329
+ return text("你已成功发送消息,可以选择结束对话")
330
+ } catch (error) {
331
+ logger.error(`${label} 发送合并转发失败`, error)
332
+ return text("error: 消息发送失败", { retryable: true })
333
+ }
334
+ }
335
+
225
336
  return await ctx.tool.transform((editor) => {
226
337
  editor.namespace({
227
338
  name: TOOL_NAMESPACE,
@@ -276,8 +387,25 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
276
387
  logger.warn(`send_message 内容长度 ${length} 超过 ${config.warnLength}`)
277
388
  }
278
389
 
279
- const chunks = splitMessage(plain)
280
390
  const operation = nextOperation()
391
+ // 太长的回复改成合并转发,别一口气刷屏。
392
+ const forwardThreshold = config.reply.forwardThresholdChars
393
+ if (forwardThreshold > 0 && length > forwardThreshold) {
394
+ return await sendAsForward(context.sessionID, target, plain, operation, length)
395
+ }
396
+
397
+ // 单段超过配置的字数就拆成多段发。
398
+ const chunks = splitMessage(plain, config.reply.segmentChars)
399
+ // 剩余额度不够分段时,宁可合并转发一条,也不要把回复截成半截。
400
+ if (forwardThreshold > 0 && chunks.length > limiter.remaining(modelSendScope(target))) {
401
+ return await sendAsForward(context.sessionID, target, plain, operation, length)
402
+ }
403
+ // 段与段之间的间隔:配了随机区间就在区间里等。
404
+ const wait = segmentDelayMs({
405
+ sendDelayMs: config.sendDelayMs,
406
+ minDelayMs: config.reply.minDelayMs,
407
+ maxDelayMs: config.reply.maxDelayMs,
408
+ })
281
409
  let sent = 0
282
410
  try {
283
411
  for (const [index, chunk] of chunks.entries()) {
@@ -287,8 +415,8 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
287
415
  const messageId = messageIdOf(response)
288
416
  if (messageId) manager.rememberOutgoing(target, messageId)
289
417
  sent += 1
290
- if (index < chunks.length - 1 && config.sendDelayMs > 0) {
291
- await delay(config.sendDelayMs)
418
+ if (index < chunks.length - 1 && wait > 0) {
419
+ await delay(wait)
292
420
  }
293
421
  }
294
422
  } catch (error) {
@@ -298,7 +426,8 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
298
426
  return text(`error: 消息只发送了 ${sent}/${chunks.length} 段`, { retryable: sent === 0 })
299
427
  }
300
428
  manager.markMessageSent(context.sessionID)
301
- logger.info(`${label} 已发送 ${length} 字`)
429
+ logger.info(`${label} 已发送 ${length} 字`, traceMeta(context.sessionID))
430
+ await traceSent(context.sessionID, target, { chars: length, mode: "plain", segments: sent })
302
431
  return text("你已成功发送消息,可以选择结束对话")
303
432
  },
304
433
  })
@@ -481,6 +610,7 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
481
610
  const messageId = messageIdOf(response)
482
611
  if (messageId) manager.rememberOutgoing(target, messageId)
483
612
  manager.markMessageSent(context.sessionID)
613
+ await traceSent(context.sessionID, target, { mode: "forward", nodes: nodes.length })
484
614
  return text("你已成功发送合并转发消息,可以选择结束对话")
485
615
  },
486
616
  })
@@ -34,8 +34,9 @@ export async function registerSendGuard(
34
34
  const last = new Map<string, LastCall>()
35
35
 
36
36
  const before = await ctx.tool.hook("execute.before", async (event) => {
37
- if (!manager.hasActiveTurn(event.sessionID)) return
38
- const turn = manager.currentTurn(event.sessionID)
37
+ const active = manager.activeTurn(event.sessionID)
38
+ if (!active) return
39
+ const turn = active.turn
39
40
  const previous = last.get(event.sessionID)
40
41
  const send = SEND_TOOL.test(event.tool)
41
42
  if (previous !== undefined && previous.turn === turn && previous.send && send) {
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
+ }