@cmach_socket/opencode-qq-bot 0.6.6 → 0.6.8

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.
@@ -20,7 +20,6 @@ import {
20
20
  type StoredImage,
21
21
  } from "./media"
22
22
 
23
- export { MAX_IMAGE_BYTES, inlineImageBytes }
24
23
  export type { PromptFile } from "./media"
25
24
 
26
25
  /** 合并转发的解析上限,避免撑爆上下文。 */
@@ -227,6 +226,36 @@ function createForwardBudget(): ForwardBudget {
227
226
  return { nodes: MAX_FORWARD_TOTAL_NODES, chars: MAX_FORWARD_TOTAL_CHARS }
228
227
  }
229
228
 
229
+ /**
230
+ * 只产出文字、不涉及媒体与上游的消息段描述。
231
+ *
232
+ * 转发内容与普通消息共用,保证两边对同一种段落的措辞一致。
233
+ *
234
+ * @returns 段落文本;需要特殊处理(@、图片、语音、引用、转发)时返回 `undefined`。
235
+ */
236
+ function describeSegment(segment: Segment): string | undefined {
237
+ switch (segment.type) {
238
+ case "text":
239
+ return sanitizeUntrustedText(segment.data.text)
240
+ case "video":
241
+ return "[视频]"
242
+ case "audio":
243
+ return "[音频]"
244
+ case "file":
245
+ return `[文件]${sanitizeUntrustedText(segment.data.name || segment.data.file)}`
246
+ case "face":
247
+ return renderFace(segment.data.id)
248
+ case "json":
249
+ return "[卡片消息]"
250
+ case "xml":
251
+ return "[XML消息]"
252
+ case "markdown":
253
+ return "[Markdown消息]"
254
+ default:
255
+ return undefined
256
+ }
257
+ }
258
+
230
259
  async function renderForwardSegments(
231
260
  ctx: RenderContext,
232
261
  message: readonly MessageSegment[],
@@ -239,10 +268,12 @@ async function renderForwardSegments(
239
268
  const images: StoredImage[] = []
240
269
  for (const segment of segments(message)) {
241
270
  try {
271
+ const described = describeSegment(segment)
272
+ if (described !== undefined) {
273
+ parts.push(described)
274
+ continue
275
+ }
242
276
  switch (segment.type) {
243
- case "text":
244
- parts.push(sanitizeUntrustedText(segment.data.text))
245
- break
246
277
  case "at":
247
278
  parts.push(`@${segment.data.qq} `)
248
279
  break
@@ -260,27 +291,6 @@ async function renderForwardSegments(
260
291
  case "record":
261
292
  parts.push("[语音]")
262
293
  break
263
- case "video":
264
- parts.push("[视频]")
265
- break
266
- case "audio":
267
- parts.push("[音频]")
268
- break
269
- case "file":
270
- parts.push(`[文件]${sanitizeUntrustedText(segment.data.name || segment.data.file)}`)
271
- break
272
- case "face":
273
- parts.push(renderFace(segment.data.id))
274
- break
275
- case "json":
276
- parts.push("[卡片消息]")
277
- break
278
- case "xml":
279
- parts.push("[XML消息]")
280
- break
281
- case "markdown":
282
- parts.push("[Markdown消息]")
283
- break
284
294
  case "reply":
285
295
  // 转发节点里的引用没有上下文,跳过
286
296
  break
@@ -387,10 +397,7 @@ export async function renderForward(
387
397
  }
388
398
 
389
399
  /** 把语音消息转成文字,转写失败时返回空字符串。 */
390
- export async function fetchVoiceText(
391
- ctx: RenderContext,
392
- messageId: number | undefined,
393
- ): Promise<string> {
400
+ async function fetchVoiceText(ctx: RenderContext, messageId: number | undefined): Promise<string> {
394
401
  if (messageId === undefined) return ""
395
402
  try {
396
403
  const result = await ctx.api.fetchPttText(messageId)
@@ -461,10 +468,12 @@ export async function renderMessage(
461
468
 
462
469
  for (const segment of message) {
463
470
  try {
471
+ const described = describeSegment(segment)
472
+ if (described !== undefined) {
473
+ textBuffer.push(described)
474
+ continue
475
+ }
464
476
  switch (segment.type) {
465
- case "text":
466
- textBuffer.push(sanitizeUntrustedText(segment.data.text))
467
- break
468
477
  case "at":
469
478
  textBuffer.push(
470
479
  `@${sanitizeSenderName(await resolveUserName(ctx, String(segment.data.qq)))} `,
@@ -516,27 +525,6 @@ export async function renderMessage(
516
525
  }
517
526
  break
518
527
  }
519
- case "video":
520
- textBuffer.push("[视频]")
521
- break
522
- case "audio":
523
- textBuffer.push("[音频]")
524
- break
525
- case "file":
526
- textBuffer.push(`[文件]${sanitizeUntrustedText(segment.data.name || segment.data.file)}`)
527
- break
528
- case "face":
529
- textBuffer.push(renderFace(segment.data.id))
530
- break
531
- case "json":
532
- textBuffer.push("[卡片消息]")
533
- break
534
- case "xml":
535
- textBuffer.push("[XML消息]")
536
- break
537
- case "markdown":
538
- textBuffer.push("[Markdown消息]")
539
- break
540
528
  default:
541
529
  ctx.logger.debug(`跳过未知消息段 type=${(segment as { type: string }).type}`)
542
530
  break
package/src/overrides.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { readFile, stat } from "node:fs/promises"
2
2
  import { join } from "node:path"
3
3
  import { type ChatTarget, targetKey } from "./chat"
4
- import { parseModelRef, type ModelRef } from "./config"
4
+ import { DEFAULT_CONFIG, parseModelRef, type ModelRef, type WakeConfig } from "./config"
5
5
  import type { Logger } from "./logger"
6
6
 
7
7
  /** 唤醒方式:决定群里的消息要不要让模型必须回复。 */
@@ -27,24 +27,13 @@ export interface WakeContext {
27
27
  text: string
28
28
  }
29
29
 
30
- /** 全局唤醒策略。 */
31
- export interface WakePolicy {
32
- /** 全局唤醒前缀,命中即必回。 */
33
- prefixes: string[]
34
- /** 是否忽略 @全体成员。 */
35
- ignoreAtAll: boolean
36
- /** 回复机器人自己的消息是否必回。 */
37
- replyToSelf: boolean
38
- /** 群里第一个 @ 指向别人时是否不唤醒机器人。 */
39
- ignoreAtOthers: boolean
40
- }
30
+ /** 全局唤醒策略:与配置项 `wake` 同构。 */
31
+ export type WakePolicy = WakeConfig
41
32
 
42
- /** 内置的全局唤醒策略。 */
33
+ /** 内置的全局唤醒策略,取自配置默认值。 */
43
34
  export const DEFAULT_WAKE_POLICY: WakePolicy = {
44
- prefixes: ["/"],
45
- ignoreAtAll: true,
46
- replyToSelf: true,
47
- ignoreAtOthers: true,
35
+ ...DEFAULT_CONFIG.wake,
36
+ prefixes: [...DEFAULT_CONFIG.wake.prefixes],
48
37
  }
49
38
 
50
39
  /** 唤醒判定的结果。 */
@@ -94,9 +83,9 @@ export function defaultChatOverrides(): ChatOverridesFile {
94
83
  return { chats: {} }
95
84
  }
96
85
 
97
- /** 默认的配置文件位置:当前工作目录下的 `chat-overrides.json`。 */
98
- export function defaultChatOverridesPath(): string {
99
- return join(process.cwd(), "chat-overrides.json")
86
+ /** 默认的配置文件位置:工作目录下的 `chat-overrides.json`。 */
87
+ export function defaultChatOverridesPath(home: string): string {
88
+ return join(home, "chat-overrides.json")
100
89
  }
101
90
 
102
91
  /**
package/src/rate-limit.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { Mutex } from "async-mutex"
2
+ import { delay } from "./async"
2
3
  import { type ChatTarget, targetKey } from "./chat"
3
4
  import type { RateLimitConfig } from "./config"
4
5
 
@@ -77,7 +78,7 @@ export class SendRateLimiter {
77
78
  }
78
79
 
79
80
  private get wait(): (ms: number) => Promise<void> {
80
- return this.options.sleep ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms)))
81
+ return this.options.sleep ?? delay
81
82
  }
82
83
 
83
84
  private lock(scope: string): Mutex {
package/src/safe-fetch.ts CHANGED
@@ -2,6 +2,7 @@ import http from "node:http"
2
2
  import https from "node:https"
3
3
  import { useAgent } from "request-filtering-agent"
4
4
  import type { Logger } from "./logger"
5
+ import { truncateForLog } from "./text"
5
6
 
6
7
  /** 允许的出站端口:只放行常见的网页端口,其余一律拒绝。 */
7
8
  export const ALLOWED_PORTS: readonly number[] = [80, 443, 8080, 8443]
@@ -36,11 +37,6 @@ export type SafeFetcher = (
36
37
  options: SafeFetchOptions,
37
38
  ) => Promise<SafeFetchResult | undefined>
38
39
 
39
- /** 截断过长的地址,避免日志被超长 URL 淹没。 */
40
- function truncateForLog(value: string, max = 120): string {
41
- return value.length > max ? `${value.slice(0, max)}…` : value
42
- }
43
-
44
40
  /**
45
41
  * 下载一个远端文件,挡住指向内网的请求。
46
42
  *
package/src/seed.ts ADDED
@@ -0,0 +1,31 @@
1
+ import { existsSync } from "node:fs"
2
+ import { copyFile, mkdir } from "node:fs/promises"
3
+ import { dirname, resolve } from "node:path"
4
+ import type { Logger } from "./logger"
5
+
6
+ /** 随包分发文件所在目录:种子文件只从这里取。 */
7
+ export const packageRoot = resolve(import.meta.dirname, "..")
8
+
9
+ /**
10
+ * 把随包分发的模板复制到工作目录。
11
+ *
12
+ * 目标已存在时原样保留:用户的改动不会被升级或重启覆盖。
13
+ *
14
+ * @returns 是否真的复制了。
15
+ */
16
+ export async function seedFile(
17
+ source: string,
18
+ destination: string,
19
+ logger: Logger,
20
+ ): Promise<boolean> {
21
+ if (existsSync(destination)) return false
22
+ try {
23
+ await mkdir(dirname(destination), { recursive: true, mode: 0o700 })
24
+ await copyFile(source, destination)
25
+ logger.info(`已放到工作目录:${destination}`)
26
+ return true
27
+ } catch (error) {
28
+ logger.warn(`复制 ${source} 失败`, error)
29
+ return false
30
+ }
31
+ }
package/src/sensitive.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { DETECTORS, redact, scan, type Detector } from "flare-redact"
2
+ import { ZERO_WIDTH } from "./text"
2
3
 
3
4
  /** 命中的敏感信息。 */
4
5
  export interface SensitiveHit {
@@ -58,9 +59,6 @@ const MIN_SECRET_LENGTH = 12
58
59
  /** 已知凭证的分片长度:够长不撞车,又短到能抓住被拆开的凭证。 */
59
60
  const FRAGMENT_LENGTH = 12
60
61
 
61
- /** 零宽字符:插在凭证中间用来骗过正则。 */
62
- const ZERO_WIDTH = /[\u200B-\u200F\u2060\uFEFF]/g
63
-
64
62
  /** 文本里像 base64 的片段。 */
65
63
  const BASE64_RUN = /[A-Za-z0-9+/_-]{20,}={0,2}/g
66
64
 
@@ -218,7 +216,7 @@ function looksLikeText(text: string): boolean {
218
216
  }
219
217
 
220
218
  /** 解一段 base64;解不出人话就返回 undefined。 */
221
- function decodeBase64(input: string): string | undefined {
219
+ function decodeBase64Text(input: string): string | undefined {
222
220
  const standard = input.replace(/-/g, "+").replace(/_/g, "/")
223
221
  const padded = standard + "=".repeat((4 - (standard.length % 4)) % 4)
224
222
  const decoded = Buffer.from(padded, "base64").toString("utf8")
@@ -233,7 +231,7 @@ function base64Variants(text: string): string[] {
233
231
  const runs = text.match(BASE64_RUN) ?? []
234
232
  const variants: string[] = []
235
233
  for (const run of runs.slice(0, MAX_BASE64_RUNS)) {
236
- const decoded = decodeBase64(run)
234
+ const decoded = decodeBase64Text(run)
237
235
  if (decoded) variants.push(decoded)
238
236
  }
239
237
  return variants
@@ -0,0 +1,45 @@
1
+ import type { Plugin } from "@opencode/plugin"
2
+ import type { Logger } from "../logger"
3
+
4
+ /** 会话列表最多翻几页。 */
5
+ const MAX_PAGES = 5
6
+ /** 每页抓多少条。 */
7
+ const PAGE_SIZE = 100
8
+
9
+ type ListResult = Awaited<ReturnType<Plugin.Context["session"]["list"]>>
10
+ /** 会话列表里的单条会话。 */
11
+ export type ListedSession = ListResult["data"][number]
12
+
13
+ /**
14
+ * 在指定目录下按谓词查找会话。
15
+ *
16
+ * 列表按创建时间倒序、翻页上限固定,避免会话很多时把整个列表拉一遍。
17
+ *
18
+ * @returns 命中的会话 ID;找不到或查询失败时返回 `undefined`。
19
+ */
20
+ export async function findSession(
21
+ ctx: Plugin.Context,
22
+ directory: NonNullable<Parameters<Plugin.Context["session"]["list"]>[0]>["directory"],
23
+ match: (session: ListedSession) => boolean,
24
+ logger: Logger,
25
+ failure: string,
26
+ ): Promise<string | undefined> {
27
+ let cursor: ListResult["cursor"]["next"] | undefined
28
+ try {
29
+ for (let page = 0; page < MAX_PAGES; page += 1) {
30
+ const result = await ctx.session.list({
31
+ directory,
32
+ limit: PAGE_SIZE,
33
+ order: "desc",
34
+ ...(cursor ? { cursor } : {}),
35
+ })
36
+ const hit = result.data.find(match)
37
+ if (hit) return hit.id
38
+ cursor = result.cursor.next ?? undefined
39
+ if (!cursor) break
40
+ }
41
+ } catch (error) {
42
+ logger.warn(failure, error)
43
+ }
44
+ return undefined
45
+ }