@cmach_socket/opencode-qq-bot 0.9.0 → 0.9.2

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.
@@ -48,6 +48,10 @@ export class PanelServer {
48
48
  private listening: { host: string; port: number } | undefined
49
49
  /** 端口被占用时的重试策略。 */
50
50
  private readonly retry: { times: number; intervalMs: number }
51
+ /** 正在应用配置:期间来的改动排队,不并行处理。 */
52
+ private applying = false
53
+ /** 排队中的改动:应用期间又来了新改动就再跑一轮。 */
54
+ private queued = false
51
55
 
52
56
  constructor(private readonly options: PanelServerOptions) {
53
57
  this.token = options.runtime.config.panel.token
@@ -68,7 +72,9 @@ export class PanelServer {
68
72
  */
69
73
  async start(): Promise<void> {
70
74
  this.unsubscribe ??= this.options.controller.onChange(() => {
71
- void this.reconcile()
75
+ void this.reconcile().catch((error: unknown) => {
76
+ this.options.logger.error("应用面板配置失败", error)
77
+ })
72
78
  })
73
79
  await this.reconcile()
74
80
  }
@@ -80,8 +86,29 @@ export class PanelServer {
80
86
  await this.closeServer()
81
87
  }
82
88
 
83
- /** 配置变了:令牌、是否启用、地址或端口都要跟着调整。 */
89
+ /**
90
+ * 配置变了:令牌、是否启用、地址或端口都要跟着调整。
91
+ *
92
+ * 一次只能应用一轮:应用期间又来的改动排队,等这一轮结束再跑。
93
+ */
84
94
  private async reconcile(): Promise<void> {
95
+ if (this.applying) {
96
+ this.queued = true
97
+ return
98
+ }
99
+ this.applying = true
100
+ try {
101
+ do {
102
+ this.queued = false
103
+ await this.apply()
104
+ } while (this.queued)
105
+ } finally {
106
+ this.applying = false
107
+ }
108
+ }
109
+
110
+ /** 应用一轮配置。 */
111
+ private async apply(): Promise<void> {
85
112
  const config = this.options.runtime.config
86
113
  // 令牌先换:面板关着的时候换了令牌,启用后也要认新的。
87
114
  if (config.panel.token !== this.token) {
@@ -93,52 +120,60 @@ export class PanelServer {
93
120
  await this.closeServer()
94
121
  return
95
122
  }
123
+ // 没有令牌就登不进去:等配置控制器补一个令牌,补完会再通知一次。
124
+ if (!config.panel.token) {
125
+ await this.closeServer()
126
+ return
127
+ }
96
128
  const host = config.panel.host
97
129
  const port = config.panel.port
98
130
  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
- })
131
+ await this.serve(host, port)
114
132
  }
115
133
 
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()
134
+ /**
135
+ * 换到新的地址与端口。
136
+ *
137
+ * 端口变了先绑新的,成功了再关旧的:绑不上时旧服务照常可用。
138
+ * 端口没变(只换了主机名)得先关旧的,同一个端口绑不了两次。
139
+ */
140
+ private async serve(host: string, port: number): Promise<void> {
122
141
  const app = createPanelApp({
123
142
  auth: this.auth,
124
143
  controller: this.options.controller,
125
144
  runtime: this.options.runtime,
126
145
  models: this.options.models,
127
- ...(existsSync(staticDir) ? { staticDir } : {}),
146
+ ...(existsSync(panelStaticDir()) ? { staticDir: panelStaticDir() } : {}),
128
147
  })
148
+ const samePort = this.listening?.port === port
149
+ if (samePort) await this.closeServer()
129
150
  const server = await this.bind(app, host, port)
130
151
  server.on("error", (error: Error) => {
131
152
  this.options.logger.error("状态面板服务出错", error)
132
153
  })
133
154
  server.unref?.()
155
+ if (!samePort) await this.closeServer()
134
156
  this.server = server
135
157
  this.listening = { host, port }
136
158
  this.options.logger.info(`状态面板已启动:http://${host}:${port}`)
137
- if (!existsSync(staticDir)) {
159
+ if (!existsSync(panelStaticDir())) {
138
160
  this.options.logger.warn("面板前端产物不存在,只有接口可用", "请执行 bun run web:build")
139
161
  }
140
162
  }
141
163
 
164
+ /** 关掉 HTTP 服务。 */
165
+ private async closeServer(): Promise<void> {
166
+ const server = this.server
167
+ this.server = undefined
168
+ this.listening = undefined
169
+ if (!server) return
170
+ await new Promise<void>((resolve) => {
171
+ server.close(() => resolve())
172
+ // SSE 的连接不会自己断,close 会一直等;强制掐掉,免得卸载卡住。
173
+ if ("closeAllConnections" in server) server.closeAllConnections()
174
+ })
175
+ }
176
+
142
177
  /**
143
178
  * 监听端口。
144
179
  *
package/src/tools/qq.ts CHANGED
@@ -7,6 +7,13 @@ import type { QQBotConfig } from "../config"
7
7
  import { dateKey, isDateKey } from "../diary/format"
8
8
  import { isDiaryScopeChat } from "../diary/scope"
9
9
  import type { DiaryStore } from "../diary/store"
10
+ import {
11
+ checkDescription,
12
+ type CollectionStore,
13
+ DESCRIPTION_RULES,
14
+ MAX_DESCRIPTION_LENGTH,
15
+ type RecentImages,
16
+ } from "../emoji/collection"
10
17
  import {
11
18
  CUSTOM_FACE_SUB_TYPE,
12
19
  type FavoriteStore,
@@ -53,6 +60,7 @@ export const QQ_TOOL_NAMES = [
53
60
  "qq_send_poke",
54
61
  "qq_delete_message",
55
62
  "qq_favorite_list",
63
+ "qq_collect_sticker",
56
64
  "qq_get_group_member_info",
57
65
  "qq_fetch_ptt_text",
58
66
  "qq_get_login_info",
@@ -72,6 +80,10 @@ export interface ToolDeps {
72
80
  favorites: FavoriteStore
73
81
  /** 收藏表情编号索引,供 qq_send_sticker 与 qq_favorite_list 使用。 */
74
82
  favoriteIndex: FavoriteIndex
83
+ /** 本机收集的表情清单,供 qq_collect_sticker 使用。 */
84
+ collection: CollectionStore
85
+ /** 各聊天最近收到的图片,供 qq_collect_sticker 找素材。 */
86
+ recentImages: RecentImages
75
87
  /** 出站限流器,所有发送类工具共用一个实例。 */
76
88
  limiter: SendRateLimiter
77
89
  /** 出站敏感信息检查,命中时整条消息不发送。 */
@@ -124,6 +136,10 @@ interface StickerInput {
124
136
  id?: number
125
137
  }
126
138
 
139
+ interface CollectStickerInput {
140
+ description?: string
141
+ }
142
+
127
143
  interface MessageIdInput {
128
144
  message_id?: number | string
129
145
  }
@@ -302,6 +318,8 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
302
318
  client,
303
319
  favorites,
304
320
  favoriteIndex,
321
+ collection,
322
+ recentImages,
305
323
  limiter,
306
324
  sensitive,
307
325
  outbound,
@@ -722,7 +740,8 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
722
740
 
723
741
  editor.add({
724
742
  name: "favorite_list",
725
- description: "列出收藏表情(表情包)的编号与标签,编号用于 qq_send_sticker 发送。",
743
+ description:
744
+ "列出收藏表情(表情包)的编号与标签,编号用于 qq_send_sticker 发送。本机收集的表情也在列表里,标注为「本机收藏」。",
726
745
  input: {
727
746
  type: "object",
728
747
  properties: {},
@@ -733,11 +752,62 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
733
752
  const prepared = prepareQuery(context.sessionID)
734
753
  if (prepared.error) return prepared.error
735
754
  const faces = await favorites.list()
736
- const rows = await favoriteIndex.sync(faces)
755
+ const rows = await favoriteIndex.sync(faces, await collection.list())
737
756
  return text(formatFavoriteList(rows))
738
757
  },
739
758
  })
740
759
 
760
+ editor.add({
761
+ name: "collect_sticker",
762
+ description: [
763
+ "收藏当前聊天里最近收到的一张动画表情(GIF 动图),收进收藏夹;",
764
+ "收藏后用 qq_send_sticker 按编号把它发回聊天。",
765
+ `description 必填:给这个表情起一个中文名字。${DESCRIPTION_RULES}`,
766
+ ].join(""),
767
+ input: {
768
+ type: "object",
769
+ properties: {
770
+ description: {
771
+ type: "string",
772
+ description: `收藏描述:中文名字,最多 ${MAX_DESCRIPTION_LENGTH} 个字,只用文字和数字,不要标点、空格、引号、解释(必填)`,
773
+ },
774
+ },
775
+ required: ["description"],
776
+ additionalProperties: false,
777
+ },
778
+ options: { namespace: TOOL_NAMESPACE, codemode: false },
779
+ execute: async (raw, context) => {
780
+ const input = (raw ?? {}) as CollectStickerInput
781
+ const prepared = prepareQuery(context.sessionID)
782
+ if (prepared.error) return prepared.error
783
+ const target = prepared.target
784
+ const checked = checkDescription(input.description)
785
+ if (!checked.ok) return text(`error: ${checked.reason}。${DESCRIPTION_RULES}`)
786
+ const image = recentImages.latest(target, { animated: true })
787
+ if (!image) {
788
+ return text("error: 这个聊天最近没有收到动画表情(GIF 动图),无法收藏")
789
+ }
790
+ let sticker
791
+ try {
792
+ sticker = await collection.add(image.file, checked.value)
793
+ } catch (error) {
794
+ logger.warn("收藏表情失败", error)
795
+ return text(`error: 收藏失败:${error instanceof Error ? error.message : String(error)}`)
796
+ }
797
+ const faces = await favorites.list()
798
+ const rows = await favoriteIndex.sync(faces, await collection.list())
799
+ // 同一张图本来就在 QQ 收藏里时,编号归那条收藏表情。
800
+ const row = rows.find((item) => {
801
+ const md5 = item.collected?.md5 ?? String(item.face.md5 ?? "").toLowerCase()
802
+ return md5 === sticker.md5
803
+ })
804
+ const age = Math.max(0, Math.round((Date.now() - image.at) / 1000))
805
+ return text(
806
+ `已收藏「${sticker.description}」,编号 ${row?.id ?? "未知"}(来自 ${age} 秒前收到的动图),之后用 qq_send_sticker 按编号发送。`,
807
+ )
808
+ },
809
+ })
810
+
741
811
  editor.add({
742
812
  name: "send_sticker",
743
813
  description:
@@ -763,7 +833,7 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
763
833
  return text("error: 缺少 id(收藏表情编号)")
764
834
  }
765
835
  const faces = await favorites.list()
766
- const rows = await favoriteIndex.sync(faces)
836
+ const rows = await favoriteIndex.sync(faces, await collection.list())
767
837
  const row = rows.find((item) => item.id === id)
768
838
  if (!row) {
769
839
  return text(`error: 没有找到编号 ${id} 的收藏表情,可用编号:${formatFavoriteIds(rows)}`)
@@ -772,15 +842,18 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
772
842
  if (!url) return text(`error: 编号 ${id} 的收藏表情缺少可用地址`)
773
843
  guardOutbound(target, url)
774
844
  // 收藏表情的地址同样来自外部,要走和图片一致的路径与地址白名单。
775
- const plan = await outbound.check(url)
845
+ let plan
846
+ try {
847
+ plan = await outbound.check(url)
848
+ } catch (error) {
849
+ return text(`error: ${error instanceof Error ? error.message : String(error)}`)
850
+ }
776
851
  const verdict = await permit(target, nextOperation())
777
852
  if (!verdict.allowed) return refuse(context.sessionID, verdict)
778
- const response = await send(target, [
779
- {
780
- type: "image",
781
- data: { file: outbound.materialize(plan), sub_type: CUSTOM_FACE_SUB_TYPE },
782
- },
783
- ])
853
+ // QQ 收藏表情带 sub_type=1(KCUSTOM);本机收集的表情不在 QQ 收藏里,按普通图片发。
854
+ const data: { file: string; sub_type?: number } = { file: outbound.materialize(plan) }
855
+ if (!row.collected) data.sub_type = CUSTOM_FACE_SUB_TYPE
856
+ const response = await send(target, [{ type: "image", data }])
784
857
  trackSent(target, response)
785
858
  manager.markMessageSent(context.sessionID)
786
859
  return text(`你已成功发送收藏表情 ${id}「${row.tag || "未标注"}」,可以选择结束对话`)