@cmach_socket/opencode-qq-bot 0.7.0 → 0.8.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/src/model-view.ts CHANGED
@@ -12,7 +12,7 @@
12
12
  import { ZERO_WIDTH } from "./text"
13
13
 
14
14
  /** 提示词里的结构标签;群友文本里出现同样字样时换成全角,避免伪造。 */
15
- const STRUCTURE_TAG = /<\/?(quote|forward|history)>/gi
15
+ const STRUCTURE_TAG = /<\/?(quote|forward|history|chat)>/gi
16
16
 
17
17
  /** 换行类字符:换行、段分隔符、下一行、垂直制表、换页。 */
18
18
  const NEWLINE_LIKE = /[\r\n\u2028\u2029\u0085\u000B\u000C]+/g
@@ -87,6 +87,8 @@ export function sanitizeSenderName(value: string): string {
87
87
  .replace(PRIVATE_USE, "")
88
88
  .replace(/[【】]/g, (char) => (char === "【" ? "[" : "]"))
89
89
  .replace(/[<>]/g, (char) => (char === "<" ? "<" : ">"))
90
+ // 括号是角色标记的写法:群名片里带着括号就能伪造出 `(owner)`。
91
+ .replace(/[()()]/g, "")
90
92
  .replace(/\s+/g, " ")
91
93
  .trim()
92
94
  )
@@ -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
+ }
@@ -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
5
+ const MAX_PAGES = 20
6
6
  /** 每页抓多少条。 */
7
- const PAGE_SIZE = 100
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 命中的会话 ID;找不到或查询失败时返回 `undefined`。
28
+ * @returns 命中的会话;找不到或查询失败时返回空数组。
19
29
  */
20
- export async function findSession(
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
- ): Promise<string | undefined> {
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 < MAX_PAGES; page += 1) {
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: PAGE_SIZE,
47
+ limit: pageSize,
33
48
  order: "desc",
34
49
  ...(cursor ? { cursor } : {}),
35
50
  })
36
- const hit = result.data.find(match)
37
- if (hit) return hit.id
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 undefined
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
  }
@@ -14,7 +14,7 @@ import type { Tracer } from "../trace"
14
14
  import { limitFiles, type PromptFile } from "../naplink/render"
15
15
  import type { WakeReason } from "../overrides"
16
16
  import { roleForChat, roleOf, type Role } from "../tools/policy"
17
- import { findSession } from "./find"
17
+ import { findSessions, type ListedSession } from "./find"
18
18
 
19
19
  /** 插件存储里保存会话与目标绑定的键。 */
20
20
  const BINDINGS_KEY = "bindings"
@@ -46,6 +46,8 @@ export const FAILURE_NOTICE_INTERVAL_MS = 5 * 60 * 1000
46
46
  export const SESSION_RETIRE_COOLDOWN_MS = 10 * 60 * 1000
47
47
  /** 交接时等在途投递落地的最长时间(毫秒)。 */
48
48
  const HANDOVER_WAIT_MS = 3_000
49
+ /** 找回历史会话时最多比较几个候选。 */
50
+ const SESSION_CANDIDATES = 5
49
51
 
50
52
  /** 插件自己往聊天里补话的通道,失败兜底用。 */
51
53
  export type FailureNotifier = (target: ChatTarget, text: string) => Promise<void>
@@ -1191,6 +1193,10 @@ export class SessionManager {
1191
1193
  state.awaitingSend = true
1192
1194
  // 新的用户轮次重新给一份提醒预算,否则连续几轮不调工具就再也提醒不了。
1193
1195
  state.reminders = 0
1196
+ // 轮次边界:发送许可只在本轮有效。新一轮无条件收回上一轮的许可,
1197
+ // 免得缓冲消息触发的新一轮带着上一轮的许可开跑。
1198
+ state.replyAllowed = false
1199
+ state.replyReason = undefined
1194
1200
  const label = targetLabel(state.target)
1195
1201
  this.logger.debug(`${label} 开始投递一轮`, {
1196
1202
  role,
@@ -1303,10 +1309,10 @@ export class SessionManager {
1303
1309
  ...(reminderRole ? { role: reminderRole } : {}),
1304
1310
  }
1305
1311
  this.logger.warn(`${label} 模型未调用发送工具,提醒第 ${state.reminders} 次`)
1306
- // 群里默认没有发送权限,提醒里得说清楚先申请再发。
1312
+ // 群里按约定不主动发言,提醒里得说清楚先说明理由再发。
1307
1313
  const permissionHint =
1308
1314
  this.config.reply.requirePermission && state.target.kind === "group"
1309
- ? "群里要先调用 qq_request_reply 说明为什么要回复,拿到权限后才能发送。"
1315
+ ? "群里要先调用 qq_request_reply 说明为什么要回复,说明之后才能发送。"
1310
1316
  : ""
1311
1317
  try {
1312
1318
  await this.ctx.session.synthetic({
@@ -1478,7 +1484,17 @@ export class SessionManager {
1478
1484
  await this.applyOverride(state.sessionID, label, agent, model)
1479
1485
  return state.sessionID
1480
1486
  }
1481
- this.unbind(state)
1487
+ // 绑定的会话取不到了:先把同一个聊天上还在的历史会话找回,找不到才新建。
1488
+ // 直接新建等于把上百条历史留在库里当孤儿,机器人再也看不见。
1489
+ const stale = state.sessionID
1490
+ const recovered = await this.recoverSession(state, target, stale)
1491
+ if (recovered) {
1492
+ this.logger.info(`${label} 旧会话 ${stale} 不可用,已改用 ${recovered}`)
1493
+ await this.applyOverride(recovered, label, agent, model)
1494
+ return recovered
1495
+ }
1496
+ // 旧会话确实没了:先松开绑定(不落盘),新建成功后一次性写回,避免中途存下空绑定。
1497
+ this.clearBinding(state)
1482
1498
  }
1483
1499
 
1484
1500
  if (this.config.reuseSession) {
@@ -1519,6 +1535,80 @@ export class SessionManager {
1519
1535
  return created.id
1520
1536
  }
1521
1537
 
1538
+ /**
1539
+ * 找回出问题时仍然存在的历史会话。
1540
+ *
1541
+ * 绑定的会话读不到时,如果直接解绑并新建,这个聊天之前积累的上下文就断了;
1542
+ * 历史会话其实还在库里,只要按 QQ 标记在同一目录里找回来就能接上。
1543
+ *
1544
+ * @returns 找回的会话 ID;没有可用的历史会话时返回 `undefined`。
1545
+ */
1546
+ private async recoverSession(
1547
+ state: ChatState,
1548
+ target: ChatTarget,
1549
+ stale: string,
1550
+ ): Promise<string | undefined> {
1551
+ const candidates = await this.findSessionCandidates(target, stale)
1552
+ if (candidates.length === 0) return undefined
1553
+ // 消息最多的那条才是真正聊过的会话:重建出来的空会话消息更少。
1554
+ const best = await this.pickRichestSession(candidates)
1555
+ if (!best) return undefined
1556
+ // 旧绑定先松开,但不能顺手把存储里的绑定抹掉:抹掉就再也找不回来了。
1557
+ this.clearBinding(state)
1558
+ if (!this.bindSession(state, best.id)) return undefined
1559
+ this.verifiedSessions.add(best.id)
1560
+ this.scheduleSave()
1561
+ return best.id
1562
+ }
1563
+
1564
+ /** 同一个聊天上仍然存在的历史会话,按最近优先。 */
1565
+ private async findSessionCandidates(
1566
+ target: ChatTarget,
1567
+ exclude?: string,
1568
+ ): Promise<ListedSession[]> {
1569
+ return await findSessions(
1570
+ this.ctx,
1571
+ this.location.directory,
1572
+ (session) => {
1573
+ const metadata = session.metadata
1574
+ if (!metadata) return false
1575
+ if (metadata["qqTargetKind"] !== target.kind) return false
1576
+ if (metadata["qqTargetId"] !== target.id) return false
1577
+ return session.id !== exclude
1578
+ },
1579
+ this.logger,
1580
+ `查找历史会话失败 ${targetLabel(target)}`,
1581
+ { limit: SESSION_CANDIDATES },
1582
+ )
1583
+ }
1584
+
1585
+ /** 选出消息最多的那条会话。 */
1586
+ private async pickRichestSession(
1587
+ candidates: ListedSession[],
1588
+ ): Promise<ListedSession | undefined> {
1589
+ let best: ListedSession | undefined
1590
+ let bestCount = -1
1591
+ for (const candidate of candidates) {
1592
+ const count = await this.countMessages(candidate.id)
1593
+ if (count > bestCount) {
1594
+ best = candidate
1595
+ bestCount = count
1596
+ }
1597
+ }
1598
+ return best
1599
+ }
1600
+
1601
+ /** 会话里的消息条数;读不到时按 0 算。 */
1602
+ private async countMessages(sessionID: string): Promise<number> {
1603
+ try {
1604
+ const messages = await this.ctx.session.context({ sessionID })
1605
+ return Array.isArray(messages) ? messages.length : 0
1606
+ } catch (error) {
1607
+ this.logger.warn(`读取会话 ${sessionID} 的消息失败`, error)
1608
+ return 0
1609
+ }
1610
+ }
1611
+
1522
1612
  /**
1523
1613
  * 把 agent / 模型覆盖应用到已有会话。
1524
1614
  *
@@ -1559,15 +1649,29 @@ export class SessionManager {
1559
1649
  this.verifiedSessions.add(sessionID)
1560
1650
  return true
1561
1651
  } catch (error) {
1652
+ // 直查只认 sessionID,列表查询才按目录过滤:两种口径不一致时,
1653
+ // 明明还在的会话会被当成已删除。直查失败后再按目录确认一次。
1654
+ if (await this.sessionInDirectory(sessionID)) {
1655
+ this.logger.warn(`会话 ${sessionID} 直查失败,但目录列表里仍然存在,继续沿用`)
1656
+ this.verifiedSessions.add(sessionID)
1657
+ return true
1658
+ }
1562
1659
  this.logger.warn(`会话 ${sessionID} 已不存在,将重新建立绑定`, error)
1563
1660
  return false
1564
1661
  }
1565
1662
  }
1566
1663
 
1567
- private unbind(state: ChatState): void {
1568
- if (!state.sessionID) return
1569
- this.clearBinding(state)
1570
- this.scheduleSave()
1664
+ /** 会话是否还在机器人的工作目录里;直查口径不一致时的兜底判断。 */
1665
+ private async sessionInDirectory(sessionID: string): Promise<boolean> {
1666
+ const found = await findSessions(
1667
+ this.ctx,
1668
+ this.location.directory,
1669
+ (session) => session.id === sessionID,
1670
+ this.logger,
1671
+ `查找会话 ${sessionID} 失败`,
1672
+ { limit: 1 },
1673
+ )
1674
+ return found.length > 0
1571
1675
  }
1572
1676
 
1573
1677
  /** 清掉会话绑定,不动上游会话。 */
@@ -1599,18 +1703,12 @@ export class SessionManager {
1599
1703
  return true
1600
1704
  }
1601
1705
 
1602
- /** 查找带相同目标标记的历史会话,按最近优先分页查找。 */
1706
+ /** 查找带相同目标标记的历史会话,按消息最多的那条优先。 */
1603
1707
  private async findExistingSession(target: ChatTarget): Promise<string | undefined> {
1604
- return await findSession(
1605
- this.ctx,
1606
- this.location.directory,
1607
- (session) => {
1608
- const metadata = session.metadata
1609
- return metadata?.["qqTargetKind"] === target.kind && metadata["qqTargetId"] === target.id
1610
- },
1611
- this.logger,
1612
- `查找历史会话失败 ${targetLabel(target)}`,
1613
- )
1708
+ const candidates = await this.findSessionCandidates(target)
1709
+ if (candidates.length === 0) return undefined
1710
+ const best = await this.pickRichestSession(candidates)
1711
+ return best?.id
1614
1712
  }
1615
1713
 
1616
1714
  /** 主动说话:向目标对应的会话投递一条合成消息。 */
@@ -7,7 +7,7 @@ GUIDELINES:
7
7
  对于一条消息,<quote>...</quote> 里面的内容是引用的消息,通常是你之前发过的消息或者其他人的消息,你需要根据这些引用来判断当前消息的语境。
8
8
  <forward>...</forward> 里面是合并转发消息的内容,每条前面的名字是转发节点的发送者。
9
9
  <history>...</history> 里面是本次会话开始之前的历史聊天记录,按时间顺序排列,用来了解之前聊过什么。
10
- 每条消息都是 \`[26-11-07 14:33] 名字(QQ号): 正文\` 这样的格式:方括号里是这条消息发出的绝对时间(本地时间),名字后面的括号里是发送者的 QQ 号,用来区分同名的人。你需要根据这些消息来判断每个用户的意图和情感。
10
+ 每条消息都是 \`[26-11-07 14:33] 名字: 正文\` 这样的格式:方括号里是这条消息发出的绝对时间(本地时间),名字后面只有 owner 和管理员才有 \`(owner)\`、\`(admin)\` 这样的角色标记,普通成员没有标记;群名片由对方自己填写,标记本身才说明身份。你需要根据这些消息来判断每个用户的意图和情感。
11
11
  重要!!!发送消息时,**必须**调用发送类工具;任何直接输出的文字都会被**完全丢弃**,不会作为消息内容发送!!!
12
12
  文本回复用 ${SEND_MESSAGE_TOOL};图片、语音、合并转发、戳一戳等用对应的 qq_* 工具,调用成功同样算作已回复。
13
13
  每轮至少调用一个发送类工具;不想回复时把 ${SEND_MESSAGE_TOOL} 的 reply 设成 false(content 可留空),相当于已读不回。群聊里不需要每一条都回复,像人一样选择性回复就行。
package/src/text.ts CHANGED
@@ -5,3 +5,37 @@ export const ZERO_WIDTH = /[\u200B-\u200F\u2060\uFEFF]/g
5
5
  export function truncateForLog(value: string, max = 120): string {
6
6
  return value.length > max ? `${value.slice(0, max)}…` : value
7
7
  }
8
+
9
+ /** 截断标记:告诉读者后面还有内容被截掉了。 */
10
+ export const TRUNCATION_MARKER = "…(已截断)"
11
+
12
+ /**
13
+ * 自然断点,按优先级排列。
14
+ *
15
+ * 先段落、再行、再句子、最后是空格:越靠前越像一个完整的意思单元。
16
+ */
17
+ const BREAKS = ["\n\n", "\n", "。", "!", "?", ";", ",", ".", "!", "?", ";", ",", " "]
18
+
19
+ /**
20
+ * 温和截断:断在自然边界上,并标出被截掉的部分。
21
+ *
22
+ * 按字数硬切会把句子拦腰砍断,读起来像坏掉了。
23
+ * 这里先按码点切出上限,再退回最后一个自然断点,末尾补上标记,
24
+ * 让人一眼看出「后面还有内容」,而不是内容凭空少了半句。
25
+ * 找不到自然断点时(整段没有标点的长串)只能按码点切,标记照常加上。
26
+ */
27
+ export function softTruncate(value: string, max: number, marker = TRUNCATION_MARKER): string {
28
+ const chars = Array.from(value)
29
+ if (chars.length <= max) return value
30
+ const tail = Array.from(marker)
31
+ const budget = max - tail.length
32
+ // 上限比标记还小:留不出标记的位置,只能按码点切。
33
+ if (budget <= 0) return chars.slice(0, Math.max(0, max)).join("")
34
+ const head = chars.slice(0, budget).join("")
35
+ for (const point of BREAKS) {
36
+ const index = head.lastIndexOf(point)
37
+ if (index <= 0) continue
38
+ return `${head.slice(0, index + point.length).trimEnd()}${marker}`
39
+ }
40
+ return `${head.trimEnd()}${marker}`
41
+ }
@@ -49,6 +49,14 @@ export interface ToolPolicyFile {
49
49
  */
50
50
  const DIARY_DENY = ["qq_diary_*", "qq_send_file"]
51
51
 
52
+ /**
53
+ * 只有 owner 能用的工具。
54
+ *
55
+ * owner 与 admin 共用 `admin` 档,所以「admin 不能用日记」只能在这里按角色判定,
56
+ * 不能写进 `admin` 档的 deny:那会把 owner 一起禁掉。
57
+ */
58
+ const OWNER_ONLY = ["qq_diary_*"]
59
+
52
60
  /** 内置默认值:普通聊天只留联网搜索、网页抓取和发消息工具,管理档全开。 */
53
61
  export function defaultToolPolicy(): ToolPolicyFile {
54
62
  return {
@@ -225,7 +233,14 @@ export class ToolPolicy {
225
233
  const file = await this.current()
226
234
  const profile = file.profiles[profileNameFor(file, role, chatKey)]
227
235
  if (!profile) return new Set(names)
228
- return new Set(allowedTools(profile, names))
236
+ const allowed = new Set(allowedTools(profile, names))
237
+ // 配置档只按工具名分配,日记这类只给 owner 的工具要在这里再按角色收一次。
238
+ if (role !== "owner") {
239
+ for (const name of allowed) {
240
+ if (OWNER_ONLY.some((pattern) => globMatch(pattern, name))) allowed.delete(name)
241
+ }
242
+ }
243
+ return allowed
229
244
  }
230
245
 
231
246
  /** 某个角色在某个聊天里生效的配置档名字,用于管理命令展示。 */