@cmach_socket/opencode-qq-bot 0.3.4 → 0.5.1
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 +63 -0
- package/README.md +170 -20
- package/package.json +20 -2
- package/src/bot-lock.ts +17 -26
- package/src/config.ts +218 -3
- package/src/emoji/command.ts +189 -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/home.ts +45 -0
- package/src/index.ts +156 -32
- 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 +130 -0
- package/src/naplink/client.ts +10 -19
- package/src/naplink/history.ts +258 -0
- package/src/naplink/media.ts +34 -103
- package/src/naplink/render.ts +96 -32
- package/src/outbound.ts +146 -0
- package/src/rate-limit.ts +161 -0
- package/src/safe-fetch.ts +143 -0
- package/src/sensitive.ts +309 -0
- package/src/session/manager.ts +232 -18
- package/src/session/prompt.ts +4 -1
- package/src/tools/ask-guard.ts +3 -2
- package/src/tools/qq.ts +218 -36
- package/src/tools/send-guard.ts +72 -0
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import type { Plugin } from "@opencode/plugin"
|
|
2
|
+
import { Mutex } from "async-mutex"
|
|
3
|
+
import type { Logger } from "../logger"
|
|
4
|
+
import { type CustomFace, faceTag, type FavoriteRow } from "./favorites"
|
|
5
|
+
|
|
6
|
+
/** 插件存储里收藏表情编号索引的键。 */
|
|
7
|
+
export const FAVORITE_INDEX_KEY = "emoji-favorite-index"
|
|
8
|
+
|
|
9
|
+
/** 编号索引用到的插件存储接口。 */
|
|
10
|
+
export type IndexStorage = Pick<Plugin.Context["storage"], "get" | "set">
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* 收藏表情的身份键。
|
|
14
|
+
*
|
|
15
|
+
* 绝对依据是图片的 `md5`:同一张图就是同一个收藏表情,NapCat 侧的
|
|
16
|
+
* `emo_id`、`res_id`、列表顺序变化都不影响认回。
|
|
17
|
+
*
|
|
18
|
+
* `md5` 缺失时退到 `res_id`,再退到 `emo_id`。
|
|
19
|
+
*/
|
|
20
|
+
export function favoriteKey(face: CustomFace): string | undefined {
|
|
21
|
+
const md5 = typeof face.md5 === "string" ? face.md5.trim().toLowerCase() : ""
|
|
22
|
+
if (md5.length > 0) return `md5:${md5}`
|
|
23
|
+
const resId = typeof face.resId === "string" ? face.resId.trim() : ""
|
|
24
|
+
if (resId.length > 0) return `res:${resId}`
|
|
25
|
+
if (face.emoId !== undefined && face.emoId !== null) return `emo:${String(face.emoId)}`
|
|
26
|
+
return undefined
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
interface StoredEntry {
|
|
30
|
+
key: string
|
|
31
|
+
id: number
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** 从插件存储里读回编号记录,格式不对就当没有。 */
|
|
35
|
+
function parseEntries(stored: unknown): StoredEntry[] {
|
|
36
|
+
if (!stored || typeof stored !== "object" || Array.isArray(stored)) return []
|
|
37
|
+
const raw = (stored as { entries?: unknown }).entries
|
|
38
|
+
if (!Array.isArray(raw)) return []
|
|
39
|
+
const entries: StoredEntry[] = []
|
|
40
|
+
for (const item of raw) {
|
|
41
|
+
if (!item || typeof item !== "object") continue
|
|
42
|
+
const { key, id } = item as { key?: unknown; id?: unknown }
|
|
43
|
+
if (typeof key !== "string" || key.length === 0) continue
|
|
44
|
+
if (typeof id !== "number" || !Number.isInteger(id) || id <= 0) continue
|
|
45
|
+
entries.push({ key, id })
|
|
46
|
+
}
|
|
47
|
+
return entries
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* 插件自维护的收藏表情编号。
|
|
52
|
+
*
|
|
53
|
+
* 编号只是发图片时的句柄,真正的身份依据是图片 `md5`;编号按首次出现的顺序
|
|
54
|
+
* 从 1 开始分配,写在插件存储里,之后每次读取都按身份键认回原来的编号,
|
|
55
|
+
* 所以 NapCat 侧的 `emo_id` 变化、列表顺序变化都不影响编号,
|
|
56
|
+
* 被删掉的收藏表情留下的编号也不会再分配给别的表情。
|
|
57
|
+
*/
|
|
58
|
+
export class FavoriteIndex {
|
|
59
|
+
private readonly entries = new Map<string, number>()
|
|
60
|
+
private readonly mutex = new Mutex()
|
|
61
|
+
private loading: Promise<void> | undefined
|
|
62
|
+
private loaded = false
|
|
63
|
+
|
|
64
|
+
constructor(
|
|
65
|
+
private readonly storage: IndexStorage,
|
|
66
|
+
private readonly logger: Logger,
|
|
67
|
+
) {}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* 读取收藏表情列表并给每个表情配上编号。
|
|
71
|
+
*
|
|
72
|
+
* 返回的顺序按编号从小到大;`md5` 相同的记录视为同一个表情,只保留一条。
|
|
73
|
+
*/
|
|
74
|
+
async sync(faces: readonly CustomFace[]): Promise<FavoriteRow[]> {
|
|
75
|
+
await this.ensureLoaded()
|
|
76
|
+
const rows: FavoriteRow[] = []
|
|
77
|
+
const seen = new Set<string>()
|
|
78
|
+
let changed = false
|
|
79
|
+
let nextId = this.nextId()
|
|
80
|
+
for (const face of faces) {
|
|
81
|
+
const key = favoriteKey(face)
|
|
82
|
+
if (!key) continue
|
|
83
|
+
if (seen.has(key)) {
|
|
84
|
+
this.logger.warn("收藏表情存在相同 md5 的重复记录,按 md5 去重")
|
|
85
|
+
continue
|
|
86
|
+
}
|
|
87
|
+
seen.add(key)
|
|
88
|
+
let id = this.entries.get(key)
|
|
89
|
+
if (id === undefined) {
|
|
90
|
+
id = nextId
|
|
91
|
+
nextId += 1
|
|
92
|
+
this.entries.set(key, id)
|
|
93
|
+
changed = true
|
|
94
|
+
}
|
|
95
|
+
rows.push({ id, face, tag: faceTag(face) })
|
|
96
|
+
}
|
|
97
|
+
rows.sort((left, right) => left.id - right.id)
|
|
98
|
+
if (changed) await this.persist()
|
|
99
|
+
return rows
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** 按编号找收藏表情;编号不存在时返回 undefined。 */
|
|
103
|
+
async resolve(faces: readonly CustomFace[], id: number): Promise<FavoriteRow | undefined> {
|
|
104
|
+
const rows = await this.sync(faces)
|
|
105
|
+
return rows.find((row) => row.id === id)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** 下一个可用的编号。 */
|
|
109
|
+
private nextId(): number {
|
|
110
|
+
let max = 0
|
|
111
|
+
for (const id of this.entries.values()) {
|
|
112
|
+
if (id > max) max = id
|
|
113
|
+
}
|
|
114
|
+
return max + 1
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** 从插件存储恢复编号索引;读取失败下次重试,不影响正常使用。 */
|
|
118
|
+
private ensureLoaded(): Promise<void> {
|
|
119
|
+
if (this.loaded) return Promise.resolve()
|
|
120
|
+
this.loading ??= this.read()
|
|
121
|
+
.then(() => {
|
|
122
|
+
this.loaded = true
|
|
123
|
+
})
|
|
124
|
+
.catch((error: unknown) => {
|
|
125
|
+
// 读取失败不缓存结果,下次调用重新读,避免索引长期为空、编号从头分配。
|
|
126
|
+
this.logger.warn("读取收藏表情编号索引失败", error)
|
|
127
|
+
this.loading = undefined
|
|
128
|
+
})
|
|
129
|
+
return this.loading
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
private async read(): Promise<void> {
|
|
133
|
+
const stored = await this.storage.get(FAVORITE_INDEX_KEY)
|
|
134
|
+
for (const entry of parseEntries(stored)) {
|
|
135
|
+
if (!this.entries.has(entry.key)) this.entries.set(entry.key, entry.id)
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** 写回编号索引,串行执行避免互相覆盖。 */
|
|
140
|
+
private async persist(): Promise<void> {
|
|
141
|
+
await this.mutex.runExclusive(async () => {
|
|
142
|
+
try {
|
|
143
|
+
const entries = [...this.entries.entries()].map(([key, id]) => ({ key, id }))
|
|
144
|
+
await this.storage.set(FAVORITE_INDEX_KEY, { version: 1, entries })
|
|
145
|
+
} catch (error) {
|
|
146
|
+
this.logger.error("保存收藏表情编号索引失败", error)
|
|
147
|
+
}
|
|
148
|
+
})
|
|
149
|
+
}
|
|
150
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { Mutex } from "async-mutex"
|
|
2
|
+
import type { Logger } from "../logger"
|
|
3
|
+
import { sanitizeUntrustedText } from "../model-view"
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* NapCat 收藏表情(自定义表情)的详情。
|
|
7
|
+
*
|
|
8
|
+
* 只声明插件用到的字段,其余字段保持原样透传。
|
|
9
|
+
*/
|
|
10
|
+
export interface CustomFace {
|
|
11
|
+
/** 表情所属的 QQ 号。 */
|
|
12
|
+
uin?: number | string
|
|
13
|
+
/** 表情编号(账号内唯一),写标签和发送时都用它。 */
|
|
14
|
+
emoId?: number | string
|
|
15
|
+
/** 资源 ID,写标签时用。 */
|
|
16
|
+
resId?: string
|
|
17
|
+
/** CDN 直链,发送收藏表情时用。 */
|
|
18
|
+
url?: string
|
|
19
|
+
/** 图片 md5,写标签时 NapCat 会校验。 */
|
|
20
|
+
md5?: string
|
|
21
|
+
/** 自定义标签;标签只存在 NapCat 的这个字段里。 */
|
|
22
|
+
desc?: string
|
|
23
|
+
[key: string]: unknown
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** OneBot 动作调用器。 */
|
|
27
|
+
export type OneBotCall = (method: string, params?: Record<string, unknown>) => Promise<unknown>
|
|
28
|
+
|
|
29
|
+
/** 收藏表情列表的缓存时长。 */
|
|
30
|
+
export const FAVORITE_CACHE_TTL_MS = 30_000
|
|
31
|
+
/** 一次拉取的收藏表情数量。 */
|
|
32
|
+
export const FAVORITE_FETCH_COUNT = 48
|
|
33
|
+
/** 收藏表情(KCUSTOM)图片段的 sub_type。 */
|
|
34
|
+
export const CUSTOM_FACE_SUB_TYPE = 1
|
|
35
|
+
|
|
36
|
+
/** 读取收藏表情上的标签,没有标签时返回空字符串。 */
|
|
37
|
+
export function faceTag(face: CustomFace): string {
|
|
38
|
+
// desc 由表情主人撰写,属于不受信任文本,进提示词前先净化。
|
|
39
|
+
return typeof face.desc === "string" ? sanitizeUntrustedText(face.desc).trim() : ""
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** 判断一个图片段是不是收藏表情。 */
|
|
43
|
+
export function isCustomFaceImage(data: { sub_type?: unknown }): boolean {
|
|
44
|
+
const subType = data.sub_type
|
|
45
|
+
return subType === CUSTOM_FACE_SUB_TYPE || subType === String(CUSTOM_FACE_SUB_TYPE)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* 收藏表情的编号与数据的对应关系。
|
|
50
|
+
*
|
|
51
|
+
* 编号由插件自己维护(见 `favorite-index.ts`),与 NapCat 的 `emo_id` 无关。
|
|
52
|
+
*/
|
|
53
|
+
export interface FavoriteRow {
|
|
54
|
+
/** 插件维护的稳定编号,从 1 开始。 */
|
|
55
|
+
id: number
|
|
56
|
+
/** 对应的收藏表情。 */
|
|
57
|
+
face: CustomFace
|
|
58
|
+
/** 收藏表情当前的标签。 */
|
|
59
|
+
tag: string
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* 列出收藏表情的编号与标签。
|
|
64
|
+
*
|
|
65
|
+
* 编号就是发送收藏表情时用的 id。
|
|
66
|
+
*/
|
|
67
|
+
export function formatFavoriteList(rows: readonly FavoriteRow[]): string {
|
|
68
|
+
if (rows.length === 0) return "没有读取到收藏表情。"
|
|
69
|
+
const lines = rows.map((row) => `${row.id}. ${row.tag || "(未标注)"}`)
|
|
70
|
+
return [`收藏表情(编号即发送用的 id,共 ${rows.length} 个)`, ...lines].join("\n")
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** 把收藏表情的编号列成一行,用于报错时提示可用编号。 */
|
|
74
|
+
export function formatFavoriteIds(rows: readonly FavoriteRow[]): string {
|
|
75
|
+
const items = rows.map((row) => (row.tag ? `${row.id}(${row.tag})` : `${row.id}`))
|
|
76
|
+
return items.length > 0 ? items.join(", ") : "(没有收藏表情)"
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* 收藏表情的读写入口。
|
|
81
|
+
*
|
|
82
|
+
* 列表带短时缓存,写标签串行执行,避免并发写坏 NapCat 侧的描述。
|
|
83
|
+
*/
|
|
84
|
+
export class FavoriteStore {
|
|
85
|
+
private readonly writeMutex = new Mutex()
|
|
86
|
+
private cache: { faces: CustomFace[]; expires: number } | undefined
|
|
87
|
+
private inflight: Promise<CustomFace[]> | undefined
|
|
88
|
+
|
|
89
|
+
constructor(
|
|
90
|
+
private readonly call: OneBotCall,
|
|
91
|
+
private readonly logger: Logger,
|
|
92
|
+
private readonly ttlMs = FAVORITE_CACHE_TTL_MS,
|
|
93
|
+
) {}
|
|
94
|
+
|
|
95
|
+
/** 读取收藏表情列表;短时间内的重复请求走缓存。 */
|
|
96
|
+
async list(options: { refresh?: boolean } = {}): Promise<CustomFace[]> {
|
|
97
|
+
if (!options.refresh) {
|
|
98
|
+
const cached = this.cache
|
|
99
|
+
if (cached && cached.expires > Date.now()) return cached.faces
|
|
100
|
+
}
|
|
101
|
+
// 先等在途请求结束,避免刷新被它吞掉;非刷新调用直接复用它的结果,
|
|
102
|
+
// 否则在途请求刚填好缓存又会多打一次接口。
|
|
103
|
+
const inflight = this.inflight
|
|
104
|
+
if (inflight) {
|
|
105
|
+
const faces = await inflight.catch(() => undefined)
|
|
106
|
+
if (!options.refresh && faces !== undefined) return faces
|
|
107
|
+
}
|
|
108
|
+
this.inflight ??= this.fetch().finally(() => {
|
|
109
|
+
this.inflight = undefined
|
|
110
|
+
})
|
|
111
|
+
return this.inflight
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
private async fetch(): Promise<CustomFace[]> {
|
|
115
|
+
try {
|
|
116
|
+
const data = await this.call("fetch_custom_face_detail", { count: FAVORITE_FETCH_COUNT })
|
|
117
|
+
const items = Array.isArray(data) ? data : []
|
|
118
|
+
const faces = items.filter(
|
|
119
|
+
(item): item is CustomFace => typeof item === "object" && item !== null,
|
|
120
|
+
)
|
|
121
|
+
this.cache = { faces, expires: Date.now() + this.ttlMs }
|
|
122
|
+
return faces
|
|
123
|
+
} catch (error) {
|
|
124
|
+
this.logger.error("读取收藏表情失败", error)
|
|
125
|
+
return this.cache?.faces ?? []
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* 写入标签。
|
|
131
|
+
*
|
|
132
|
+
* 标签只写在 NapCat 的 `desc` 字段里,插件不保存副本。
|
|
133
|
+
*/
|
|
134
|
+
async setTag(face: CustomFace, tag: string): Promise<boolean> {
|
|
135
|
+
const { emoId, resId, md5 } = face
|
|
136
|
+
if (emoId === undefined || !resId || !md5) {
|
|
137
|
+
this.logger.warn("收藏表情缺少 emoId/res_id/md5,无法写入标签")
|
|
138
|
+
return false
|
|
139
|
+
}
|
|
140
|
+
return this.writeMutex.runExclusive(async () => {
|
|
141
|
+
try {
|
|
142
|
+
await this.call("set_custom_face_desc", {
|
|
143
|
+
emoji_id: emoId,
|
|
144
|
+
res_id: resId,
|
|
145
|
+
md5,
|
|
146
|
+
desc: tag,
|
|
147
|
+
})
|
|
148
|
+
this.invalidate()
|
|
149
|
+
return true
|
|
150
|
+
} catch (error) {
|
|
151
|
+
this.logger.error(`写入收藏表情标签失败 res_id=${resId}`, error)
|
|
152
|
+
return false
|
|
153
|
+
}
|
|
154
|
+
})
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** 让缓存失效,下次读取重新拉取。 */
|
|
158
|
+
invalidate(): void {
|
|
159
|
+
this.cache = undefined
|
|
160
|
+
}
|
|
161
|
+
}
|
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
import type { Plugin } from "@opencode/plugin"
|
|
2
|
+
import type { Location } from "@opencode/schema"
|
|
3
|
+
import type { QQBotConfig } from "../config"
|
|
4
|
+
import type { BotHome } from "../home"
|
|
5
|
+
import type { Logger } from "../logger"
|
|
6
|
+
import type { MediaStore } from "../naplink/media"
|
|
7
|
+
import type { CustomFace, FavoriteStore } from "./favorites"
|
|
8
|
+
|
|
9
|
+
/** 标签最长字符数。 */
|
|
10
|
+
export const MAX_TAG_LENGTH = 12
|
|
11
|
+
/** 单个表情等待模型回复的超时时间。 */
|
|
12
|
+
export const LABEL_TIMEOUT_MS = 60_000
|
|
13
|
+
/** 插件存储里保存标签会话 ID 的键。 */
|
|
14
|
+
export const LABEL_SESSION_KEY = "emoji-label-session"
|
|
15
|
+
/** 会话标记:用来找回已经建好的标签会话。 */
|
|
16
|
+
export const LABEL_SESSION_MARKER = "qqEmojiLabelSession"
|
|
17
|
+
|
|
18
|
+
/** 让模型只回一个标签的提示词。 */
|
|
19
|
+
export const LABEL_PROMPT = [
|
|
20
|
+
"看这张表情包图片,给它起一个中文名字。",
|
|
21
|
+
`要求:只输出名字本身,一行,最多 ${MAX_TAG_LENGTH} 个字,不要标点、引号、解释或其它文字。`,
|
|
22
|
+
"不要调用任何工具。",
|
|
23
|
+
].join("\n")
|
|
24
|
+
|
|
25
|
+
function delay(ms: number): Promise<void> {
|
|
26
|
+
return new Promise((resolve) => setTimeout(resolve, ms))
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* 清理模型给出的标签。
|
|
31
|
+
*
|
|
32
|
+
* 取第一行,去掉列表符号、引号和 markdown 装饰,只保留文字与数字,
|
|
33
|
+
* 最后按码点截断到 12 个字。
|
|
34
|
+
*/
|
|
35
|
+
export function cleanTag(raw: string): string {
|
|
36
|
+
const line = raw
|
|
37
|
+
.split(/\r?\n/)
|
|
38
|
+
.map((item) => item.trim())
|
|
39
|
+
.find((item) => item.length > 0)
|
|
40
|
+
if (!line) return ""
|
|
41
|
+
const stripped = line
|
|
42
|
+
.replace(/^[*_~`>]+/, "")
|
|
43
|
+
.replace(/^[-+•·–—]+\s*/, "")
|
|
44
|
+
.replace(/^\d+[.、))]\s*/, "")
|
|
45
|
+
.replace(/^#+\s*/, "")
|
|
46
|
+
.replace(/[“”"'「」『』‘’`]+/g, "")
|
|
47
|
+
const chars = Array.from(stripped).filter((char) => /[\p{L}\p{N}]/u.test(char))
|
|
48
|
+
return chars.slice(0, MAX_TAG_LENGTH).join("")
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface LabelerDeps {
|
|
52
|
+
ctx: Plugin.Context
|
|
53
|
+
config: QQBotConfig
|
|
54
|
+
/** 机器人固定服务的工作目录,标签会话也建在这里。 */
|
|
55
|
+
home: BotHome
|
|
56
|
+
logger: Logger
|
|
57
|
+
/** 图片下载与落盘。 */
|
|
58
|
+
media: MediaStore
|
|
59
|
+
/** 标签读写。 */
|
|
60
|
+
favorites: FavoriteStore
|
|
61
|
+
/** 单个表情的等待时间。 */
|
|
62
|
+
timeoutMs?: number
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* 用模型给收藏表情起名字。
|
|
67
|
+
*
|
|
68
|
+
* 走一个专用的会话:这个会话不绑定任何 QQ 目标,
|
|
69
|
+
* 因此不会触发角色设定里“必须调用 qq_send_message”的守则。
|
|
70
|
+
*/
|
|
71
|
+
export class EmojiLabeler {
|
|
72
|
+
private readonly abort = new AbortController()
|
|
73
|
+
/** 每个会话当前这一轮累积到的回复文本。 */
|
|
74
|
+
private readonly buffers = new Map<string, string>()
|
|
75
|
+
/** 等待本轮回复结束的回调。 */
|
|
76
|
+
private readonly waiters = new Map<string, ((text: string | undefined) => void)[]>()
|
|
77
|
+
private listener: Promise<void> | undefined
|
|
78
|
+
private sessionID: string | undefined
|
|
79
|
+
private creating: Promise<string> | undefined
|
|
80
|
+
|
|
81
|
+
constructor(private readonly deps: LabelerDeps) {}
|
|
82
|
+
|
|
83
|
+
/** 标签会话统一落在机器人工作目录,不跟随加载插件的项目目录。 */
|
|
84
|
+
private get location(): Location.PublicRef {
|
|
85
|
+
return { directory: this.deps.home.directory as Location.PublicRef["directory"] }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** 标注是否已中止;插件卸载后应停止一切标注动作。 */
|
|
89
|
+
get signal(): AbortSignal {
|
|
90
|
+
return this.abort.signal
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** 开始订阅文本事件。 */
|
|
94
|
+
start(): void {
|
|
95
|
+
this.listener ??= this.listen()
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** 停止订阅并清理缓存。 */
|
|
99
|
+
async dispose(): Promise<void> {
|
|
100
|
+
this.abort.abort()
|
|
101
|
+
this.buffers.clear()
|
|
102
|
+
// 唤醒还在等待的标注请求,让它们立刻结束而不是空等到超时。
|
|
103
|
+
for (const waiters of this.waiters.values()) {
|
|
104
|
+
for (const resolve of waiters) resolve(undefined)
|
|
105
|
+
}
|
|
106
|
+
this.waiters.clear()
|
|
107
|
+
await this.listener?.catch(() => {})
|
|
108
|
+
this.listener = undefined
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
private async listen(): Promise<void> {
|
|
112
|
+
while (!this.abort.signal.aborted) {
|
|
113
|
+
try {
|
|
114
|
+
for await (const event of this.deps.ctx.event.subscribe({
|
|
115
|
+
// 一轮回复可能拆成多段文本,只有执行结束才知道这一轮说完了。
|
|
116
|
+
types: [
|
|
117
|
+
"session.text.ended",
|
|
118
|
+
"session.execution.succeeded",
|
|
119
|
+
"session.execution.failed",
|
|
120
|
+
"session.execution.interrupted",
|
|
121
|
+
],
|
|
122
|
+
signal: this.abort.signal,
|
|
123
|
+
})) {
|
|
124
|
+
if (event.type === "session.text.ended") {
|
|
125
|
+
this.push(event.data.sessionID, event.data.text)
|
|
126
|
+
} else if (event.type === "session.execution.succeeded") {
|
|
127
|
+
this.finish(event.data.sessionID)
|
|
128
|
+
} else {
|
|
129
|
+
this.fail(event.data.sessionID)
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
} catch (error) {
|
|
133
|
+
if (this.abort.signal.aborted) return
|
|
134
|
+
this.deps.logger.error("订阅表情标签事件失败,稍后重试", error)
|
|
135
|
+
}
|
|
136
|
+
if (this.abort.signal.aborted) return
|
|
137
|
+
await delay(1000)
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** 累加模型输出的一段文本;一轮回复可能拆成多段。 */
|
|
142
|
+
private push(sessionID: string, text: string): void {
|
|
143
|
+
const buffer = `${this.buffers.get(sessionID) ?? ""}${text}`
|
|
144
|
+
this.buffers.set(sessionID, buffer)
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** 本轮执行结束:把累积到的完整文本交给等待方。 */
|
|
148
|
+
private finish(sessionID: string): void {
|
|
149
|
+
const waiters = this.waiters.get(sessionID)
|
|
150
|
+
if (!waiters || waiters.length === 0) return
|
|
151
|
+
this.waiters.delete(sessionID)
|
|
152
|
+
const text = this.buffers.get(sessionID) ?? ""
|
|
153
|
+
for (const resolve of waiters) resolve(text)
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** 本轮执行失败或被中断:没有可用回复。 */
|
|
157
|
+
private fail(sessionID: string): void {
|
|
158
|
+
const waiters = this.waiters.get(sessionID)
|
|
159
|
+
if (!waiters || waiters.length === 0) return
|
|
160
|
+
this.waiters.delete(sessionID)
|
|
161
|
+
for (const resolve of waiters) resolve(undefined)
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** 等待这一轮的完整回复;超时或执行失败返回 undefined。 */
|
|
165
|
+
private awaitText(sessionID: string, timeoutMs: number): Promise<string | undefined> {
|
|
166
|
+
const buffered = this.buffers.get(sessionID)
|
|
167
|
+
if (buffered && buffered.length > 0) {
|
|
168
|
+
this.buffers.delete(sessionID)
|
|
169
|
+
return Promise.resolve(buffered)
|
|
170
|
+
}
|
|
171
|
+
return new Promise((resolve) => {
|
|
172
|
+
const onText = (text: string | undefined) => {
|
|
173
|
+
clearTimeout(timer)
|
|
174
|
+
resolve(text)
|
|
175
|
+
}
|
|
176
|
+
const timer = setTimeout(() => {
|
|
177
|
+
const waiters = this.waiters.get(sessionID) ?? []
|
|
178
|
+
this.waiters.set(
|
|
179
|
+
sessionID,
|
|
180
|
+
waiters.filter((item) => item !== onText),
|
|
181
|
+
)
|
|
182
|
+
resolve(undefined)
|
|
183
|
+
}, timeoutMs)
|
|
184
|
+
const waiters = this.waiters.get(sessionID) ?? []
|
|
185
|
+
waiters.push(onText)
|
|
186
|
+
this.waiters.set(sessionID, waiters)
|
|
187
|
+
})
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** 取得(必要时创建)专用的标签会话。 */
|
|
191
|
+
private async ensureSession(): Promise<string> {
|
|
192
|
+
if (this.sessionID) return this.sessionID
|
|
193
|
+
this.creating ??= this.resolveSession().finally(() => {
|
|
194
|
+
this.creating = undefined
|
|
195
|
+
})
|
|
196
|
+
return this.creating
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
private async resolveSession(): Promise<string> {
|
|
200
|
+
const stored = await this.readStoredSession()
|
|
201
|
+
if (stored) {
|
|
202
|
+
this.sessionID = stored
|
|
203
|
+
return stored
|
|
204
|
+
}
|
|
205
|
+
const found = await this.findLabelSession()
|
|
206
|
+
if (found) {
|
|
207
|
+
this.sessionID = found
|
|
208
|
+
await this.writeStoredSession(found)
|
|
209
|
+
this.deps.logger.info(`复用表情标签会话 ${found}`)
|
|
210
|
+
return found
|
|
211
|
+
}
|
|
212
|
+
const created = await this.deps.ctx.session.create({
|
|
213
|
+
title: "收藏表情标签",
|
|
214
|
+
location: this.location,
|
|
215
|
+
...(this.deps.config.agent ? { agent: this.deps.config.agent } : {}),
|
|
216
|
+
...(this.deps.config.model ? { model: this.deps.config.model } : {}),
|
|
217
|
+
metadata: { [LABEL_SESSION_MARKER]: true },
|
|
218
|
+
})
|
|
219
|
+
this.sessionID = created.id
|
|
220
|
+
await this.writeStoredSession(created.id)
|
|
221
|
+
this.deps.logger.info(`新建表情标签会话 ${created.id}`)
|
|
222
|
+
return created.id
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
private async readStoredSession(): Promise<string | undefined> {
|
|
226
|
+
try {
|
|
227
|
+
const stored = await this.deps.ctx.storage.get(LABEL_SESSION_KEY)
|
|
228
|
+
if (typeof stored !== "string" || stored.length === 0) return undefined
|
|
229
|
+
const info = await this.deps.ctx.session.get({ sessionID: stored })
|
|
230
|
+
if (info?.location?.directory !== this.location.directory) {
|
|
231
|
+
this.deps.logger.debug(`存储里的标签会话 ${stored} 不在机器人工作目录,忽略`)
|
|
232
|
+
return undefined
|
|
233
|
+
}
|
|
234
|
+
return info?.id ?? stored
|
|
235
|
+
} catch (error) {
|
|
236
|
+
this.deps.logger.debug("读取收藏表情标签会话失败,将新建会话", error)
|
|
237
|
+
return undefined
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
private async writeStoredSession(sessionID: string): Promise<void> {
|
|
242
|
+
try {
|
|
243
|
+
await this.deps.ctx.storage.set(LABEL_SESSION_KEY, sessionID)
|
|
244
|
+
} catch (error) {
|
|
245
|
+
this.deps.logger.warn("保存收藏表情标签会话失败", error)
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** 查找带标签标记的历史会话。 */
|
|
250
|
+
private async findLabelSession(): Promise<string | undefined> {
|
|
251
|
+
let cursor: string | undefined
|
|
252
|
+
try {
|
|
253
|
+
for (let page = 0; page < 5; page += 1) {
|
|
254
|
+
const result = await this.deps.ctx.session.list({
|
|
255
|
+
directory: this.location.directory,
|
|
256
|
+
limit: 100,
|
|
257
|
+
order: "desc",
|
|
258
|
+
...(cursor ? { cursor } : {}),
|
|
259
|
+
})
|
|
260
|
+
const hit = result.data.find((session) => session.metadata?.[LABEL_SESSION_MARKER] === true)
|
|
261
|
+
if (hit) return hit.id
|
|
262
|
+
cursor = result.cursor.next ?? undefined
|
|
263
|
+
if (!cursor) break
|
|
264
|
+
}
|
|
265
|
+
} catch (error) {
|
|
266
|
+
this.deps.logger.warn("查找收藏表情标签会话失败", error)
|
|
267
|
+
}
|
|
268
|
+
return undefined
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* 给一个表情生成标签并写回 NapCat。
|
|
273
|
+
*
|
|
274
|
+
* 返回写进去的标签;下载失败、模型没给出可用名字或写入失败时返回 undefined。
|
|
275
|
+
*/
|
|
276
|
+
async labelFace(face: CustomFace): Promise<string | undefined> {
|
|
277
|
+
// 插件卸载后不再发起新的标注请求。
|
|
278
|
+
if (this.abort.signal.aborted) return undefined
|
|
279
|
+
const url = typeof face.url === "string" ? face.url : undefined
|
|
280
|
+
if (!url) return undefined
|
|
281
|
+
const stored = await this.deps.media.storeImage(url)
|
|
282
|
+
if (!stored) {
|
|
283
|
+
this.deps.logger.warn("收藏表情图片下载失败,跳过标注")
|
|
284
|
+
return undefined
|
|
285
|
+
}
|
|
286
|
+
this.start()
|
|
287
|
+
const sessionID = await this.ensureSession()
|
|
288
|
+
// 丢掉上一轮的残留文本,保证拿到的是这次提问的回复。
|
|
289
|
+
this.buffers.delete(sessionID)
|
|
290
|
+
try {
|
|
291
|
+
await this.deps.ctx.session.prompt({
|
|
292
|
+
sessionID,
|
|
293
|
+
text: LABEL_PROMPT,
|
|
294
|
+
files: [
|
|
295
|
+
{
|
|
296
|
+
uri: stored.uri,
|
|
297
|
+
name: stored.name,
|
|
298
|
+
...(stored.source ? { source: stored.source } : {}),
|
|
299
|
+
},
|
|
300
|
+
],
|
|
301
|
+
})
|
|
302
|
+
} catch (error) {
|
|
303
|
+
this.deps.logger.error("投递表情标签请求失败", error)
|
|
304
|
+
return undefined
|
|
305
|
+
}
|
|
306
|
+
const raw = await this.awaitText(sessionID, this.deps.timeoutMs ?? LABEL_TIMEOUT_MS)
|
|
307
|
+
// 等回复期间插件可能已经卸载,此时不再写标签。
|
|
308
|
+
if (this.abort.signal.aborted) return undefined
|
|
309
|
+
const tag = cleanTag(raw ?? "")
|
|
310
|
+
if (!tag) {
|
|
311
|
+
this.deps.logger.warn("模型没有给出可用的表情标签")
|
|
312
|
+
return undefined
|
|
313
|
+
}
|
|
314
|
+
const written = await this.deps.favorites.setTag(face, tag)
|
|
315
|
+
if (!written) return undefined
|
|
316
|
+
return tag
|
|
317
|
+
}
|
|
318
|
+
}
|
package/src/home.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { mkdir } from "node:fs/promises"
|
|
2
|
+
import { homedir } from "node:os"
|
|
3
|
+
import { isAbsolute, join, normalize } from "node:path"
|
|
4
|
+
import type { Logger } from "./logger"
|
|
5
|
+
|
|
6
|
+
/** 机器人固定服务的工作目录。 */
|
|
7
|
+
export interface BotHome {
|
|
8
|
+
/** 会话统一所在的绝对路径。 */
|
|
9
|
+
directory: string
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** 默认工作目录:`$XDG_DATA_HOME/opencode-qq-bot/workspace`。 */
|
|
13
|
+
export function defaultHome(): string {
|
|
14
|
+
const data = process.env.XDG_DATA_HOME
|
|
15
|
+
const base = data && isAbsolute(data) ? data : join(homedir(), ".local", "share")
|
|
16
|
+
return join(base, "opencode-qq-bot", "workspace")
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* 解析机器人工作目录并确保它存在。
|
|
21
|
+
*
|
|
22
|
+
* 配置项优先;未配置时使用默认的 XDG 工作区,避免会话工作目录随加载插件的项目漂移。
|
|
23
|
+
*/
|
|
24
|
+
export async function resolveHome(
|
|
25
|
+
configured: string | undefined,
|
|
26
|
+
logger: Logger,
|
|
27
|
+
): Promise<BotHome> {
|
|
28
|
+
const directory = configured ? expand(configured, logger) : defaultHome()
|
|
29
|
+
await mkdir(directory, { recursive: true, mode: 0o700 })
|
|
30
|
+
return { directory }
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function expand(configured: string, logger: Logger): string {
|
|
34
|
+
const expanded =
|
|
35
|
+
configured === "~"
|
|
36
|
+
? homedir()
|
|
37
|
+
: configured.startsWith("~/")
|
|
38
|
+
? join(homedir(), configured.slice(2))
|
|
39
|
+
: configured
|
|
40
|
+
if (!isAbsolute(expanded)) {
|
|
41
|
+
logger.warn("机器人工作目录必须是绝对路径,已回退到默认目录", configured)
|
|
42
|
+
return defaultHome()
|
|
43
|
+
}
|
|
44
|
+
return normalize(expanded)
|
|
45
|
+
}
|