dsh-chat-comprehension 0.3.2 → 0.3.6
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/README.md +105 -114
- package/client.js +399 -23
- package/lib/index.js +125 -0
- package/lib/net.mjs +97 -0
- package/lib/qqbot-0.5.3-patches.json +42 -1
- package/lib/qqbot-patch.mjs +17 -9
- package/lib/setup.mjs +431 -0
- package/lib/video.mjs +47 -2
- package/package.json +1 -1
- package/vendor/dsh-agent-md/lib/chat-models.js +116 -0
- package/vendor/dsh-agent-md/lib/chat-persona.js +207 -0
- package/vendor/dsh-agent-md/lib/chat-workspaces.js +81 -0
- package/vendor/dsh-agent-md/lib/index.js +108 -0
- package/vendor/dsh-bili-scroll/index.js +15 -6
- package/vendor/dsh-bili-scroll/prompts/duty.md +6 -3
- package/vendor/dsh-meme/memes.js +1003 -998
package/vendor/dsh-meme/memes.js
CHANGED
|
@@ -1,998 +1,1003 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 表情包存储与搜索(dsh-expression 插件)。
|
|
3
|
-
*
|
|
4
|
-
* 模型侧两种搜法:①按 6 个情绪桶选 tag,从桶里随机抽若干张;②按关键词
|
|
5
|
-
* 在 caption/关键词/图名里子串搜(全部关键词命中优先)。两个都给 = 在该
|
|
6
|
-
* 情绪里筛关键词。候选都带 caption,模型看描述觉得贴再发。
|
|
7
|
-
*/
|
|
8
|
-
import { DatabaseSync } from 'node:sqlite'
|
|
9
|
-
import { basename, dirname, join, resolve, sep } from 'node:path'
|
|
10
|
-
import { homedir } from 'node:os'
|
|
11
|
-
import { fileURLToPath } from 'node:url'
|
|
12
|
-
import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
|
|
13
|
-
import { defineTool } from '@deepseek-ai/dsh-tools'
|
|
14
|
-
|
|
15
|
-
/** 内置图库根目录:插件包内 memes/<id>/(随包分发的只有 dafeiyu-001)。 */
|
|
16
|
-
export function bundledPacksDir() {
|
|
17
|
-
return fileURLToPath(new URL('./memes', import.meta.url))
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
/**
|
|
21
|
-
* dsh 的 home 目录(设置/图库扫描目录的根)。
|
|
22
|
-
* 用 os.homedir() 而不是 process.env.HOME:Windows 上通常没有 HOME,
|
|
23
|
-
* 回落成 '.' 会让设置文件和扫描目录跟着 CWD 走(历史 bug:.dsh\meme-packs 变相对路径)。
|
|
24
|
-
* 测试用 DSH_MEME_HOME 覆盖到临时目录。
|
|
25
|
-
*/
|
|
26
|
-
export function dshHome() {
|
|
27
|
-
return process.env.DSH_MEME_HOME || homedir()
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
/** 内置默认图库根:随插件分发的 memes/dafeiyu-001(大肥鱼)。可用 memeRoot 覆盖。 */
|
|
31
|
-
export function defaultMemeRoot() {
|
|
32
|
-
return join(bundledPacksDir(), 'dafeiyu-001')
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
/** 用户导入/自建图库的扫描目录。 */
|
|
36
|
-
export function defaultPacksDir() {
|
|
37
|
-
return join(dshHome(), '.dsh', 'meme-packs')
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
/**
|
|
41
|
-
* 本插件包自己的根目录。
|
|
42
|
-
* 装成插件时就是 `node_modules/dsh-meme`;插件市场更新会用 pnpm 把整个目录改名替换。
|
|
43
|
-
* @param {string} [fromDir] 测试用:以某个目录作为「插件包根」,不传则按本模块位置推。
|
|
44
|
-
*/
|
|
45
|
-
export function pluginPackageDir(fromDir) {
|
|
46
|
-
return fromDir ? resolve(fromDir) : resolve(bundledPacksDir(), '..')
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
/**
|
|
50
|
-
* dir 是否落在插件包目录里。
|
|
51
|
-
*
|
|
52
|
-
* 为什么关心这件事:内置图库在 `<插件包>/memes/<id>` 里,用户在上面学图/上传时
|
|
53
|
-
* 插件会写这个目录。Windows 上目录里只要有打开的文件句柄,`rename` 该目录(或它的
|
|
54
|
-
* 祖先)就报 `EPERM`;而 pnpm 更新正是 rename 整个包目录 → 插件更新失败(issue #43)。
|
|
55
|
-
* 包内路径上的 SQLite 连接一律不常驻,见 openIndexWriter。
|
|
56
|
-
* @param {string} dir 要判断的目录
|
|
57
|
-
* @param {string} [packageDir] 插件包根目录(默认按本模块位置推;测试可传)
|
|
58
|
-
*/
|
|
59
|
-
export function isInsidePluginPackage(dir, packageDir) {
|
|
60
|
-
try {
|
|
61
|
-
const target = resolve(dir)
|
|
62
|
-
const pkg = pluginPackageDir(packageDir)
|
|
63
|
-
return target === pkg || target.startsWith(pkg + sep)
|
|
64
|
-
} catch {
|
|
65
|
-
return false
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
/**
|
|
70
|
-
* 删除图库时该删哪个目录。只认两种路径,别的一律拒绝(防越界/防误删):
|
|
71
|
-
* - 内置包:插件包内 `memes/<id>`
|
|
72
|
-
* - 用户包:扫描目录子树里一个真正的包目录(`<packsDir>/<id>`,或历史遗留的嵌套包)
|
|
73
|
-
* @param {{id?: string, path?: string, source?: string}} pack listAllPacks() 的一项
|
|
74
|
-
* @param {string} packsDir 当前扫描目录
|
|
75
|
-
*/
|
|
76
|
-
export function packDeleteDir(pack, packsDir) {
|
|
77
|
-
const id = String((pack && pack.id) || '').trim()
|
|
78
|
-
if (!pack || !pack.path || !id) throw new Error('图库信息不完整')
|
|
79
|
-
const dir = resolve(pack.path)
|
|
80
|
-
if (pack.source === 'bundled') {
|
|
81
|
-
if (dir !== resolve(join(bundledPacksDir(), id))) throw new Error('图库目录与预期不符,已拒绝删除')
|
|
82
|
-
return dir
|
|
83
|
-
}
|
|
84
|
-
// 用户包:以前只认 `<packsDir>/<id>` 这一层,于是历史遗留的嵌套包(见 scanPacks)
|
|
85
|
-
// 能列在设置页里却删不掉。放宽成「packsDir 子树 + 目录名正好是包 id」,多层嵌套可删,
|
|
86
|
-
// 但仍然碰不到扫描目录本身,也删不到扫描目录外面的任何东西。
|
|
87
|
-
const root = resolve(String(packsDir || ''))
|
|
88
|
-
if (!root) throw new Error('图库目录无效,已拒绝删除')
|
|
89
|
-
if (dir === root) throw new Error('这个图库就是当前的「图库目录」本身,请先把它改到上级目录再删')
|
|
90
|
-
if (basename(dir) === id && dir.startsWith(root + sep)) return dir
|
|
91
|
-
throw new Error('图库目录与预期不符,已拒绝删除')
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
/**
|
|
95
|
-
* 模型可以用的图库 id 列表(设置页每张卡片上的开关)。
|
|
96
|
-
* 没设置过 `enabledPacks` 时只算当前图库——保持「装完即用」的旧行为,
|
|
97
|
-
* 用户一旦拨过开关就以显式列表为准(可以同时开多个)。
|
|
98
|
-
* 已删除/已卸载的 id 会被过滤掉。
|
|
99
|
-
*/
|
|
100
|
-
export function enabledPackIds(settings = {}, packs = [], activeId = '') {
|
|
101
|
-
const saved = Array.isArray(settings.enabledPacks) ? settings.enabledPacks.map(String) : null
|
|
102
|
-
if (saved === null) return activeId ? [activeId] : []
|
|
103
|
-
const alive = new Set(packs.map((p) => p.id))
|
|
104
|
-
return saved.filter((id) => alive.has(id))
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
export function isPackDir(dir) {
|
|
108
|
-
try {
|
|
109
|
-
return statSync(dir).isDirectory() && existsSync(join(dir, 'index.db'))
|
|
110
|
-
} catch {
|
|
111
|
-
return false
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
/** 读 manifest + 张数。id 以文件夹名为准(切换键稳定)。 */
|
|
116
|
-
export function readPackMeta(dir, id = basename(dir), source = 'custom') {
|
|
117
|
-
let name = id
|
|
118
|
-
let description = ''
|
|
119
|
-
let version = ''
|
|
120
|
-
try {
|
|
121
|
-
const m = JSON.parse(readFileSync(join(dir, 'manifest.json'), 'utf8'))
|
|
122
|
-
if (m && m.name) name = String(m.name)
|
|
123
|
-
if (m && m.description) description = String(m.description)
|
|
124
|
-
if (m && m.version) version = String(m.version)
|
|
125
|
-
} catch { /* 无 manifest 也能当包用 */ }
|
|
126
|
-
let count = 0
|
|
127
|
-
let cover = ''
|
|
128
|
-
try {
|
|
129
|
-
const db = new DatabaseSync(join(dir, 'index.db'), { readOnly: true })
|
|
130
|
-
count = Number(db.prepare('SELECT COUNT(*) AS n FROM memes').get().n) || 0
|
|
131
|
-
// 封面用图库自己的一张图(相对路径),装完的那份就在本地,不必再拉远程预览图。
|
|
132
|
-
// 取法固定:优先 happy 桶里字典序第一张,保证同一图库每次算出来同一张。
|
|
133
|
-
const row = db.prepare("SELECT path FROM memes ORDER BY (tag = 'happy') DESC, path ASC LIMIT 1").get()
|
|
134
|
-
if (row && row.path) cover = String(row.path)
|
|
135
|
-
db.close()
|
|
136
|
-
} catch { /* 空库或坏库 */ }
|
|
137
|
-
return { id, name, description, version, count, cover, path: resolve(dir), source }
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
/**
|
|
141
|
-
* 扫描可切换图库:插件内置 memes/* + 用户扫描目录下的一层子文件夹。
|
|
142
|
-
* 同 id 时用户目录覆盖内置(方便自己改官方包),同层里顶层优先。
|
|
143
|
-
*
|
|
144
|
-
* 历史遗留(issue #23):扫描目录被设成某个包目录自己时(设置页「选择目录」很容易点到包
|
|
145
|
-
* 文件夹),之后导入的包会嵌在那个包里面 → `memes/<主库>/<子库>/index.db`。这不是设计内的
|
|
146
|
-
* 布局,但已经躺在用户磁盘上了,所以这里额外容忍两种形状,免得图库「在磁盘上却扫不到」:
|
|
147
|
-
* 1. 扫描目录本身就是包 → 也当包收进来,否则它自己会从列表里消失(比嵌套更迷惑)
|
|
148
|
-
* 2. 包目录下再嵌一层包 → 一起收(顶层优先,同 id 不覆盖)
|
|
149
|
-
* 新导入不会再生成这种布局:setPacksDir 拒绝把包目录当扫描目录。
|
|
150
|
-
*/
|
|
151
|
-
export function scanPacks(packsDir = defaultPacksDir()) {
|
|
152
|
-
const byId = new Map()
|
|
153
|
-
const addPack = (dir, id, source) => {
|
|
154
|
-
if (!id || byId.has(id)) return
|
|
155
|
-
byId.set(id, readPackMeta(dir, id, source))
|
|
156
|
-
}
|
|
157
|
-
const addFrom = (parent, source) => {
|
|
158
|
-
if (!parent || !existsSync(parent)) return
|
|
159
|
-
if (isPackDir(parent)) addPack(parent, basename(parent), source)
|
|
160
|
-
let names
|
|
161
|
-
try { names = readdirSync(parent) } catch { return }
|
|
162
|
-
for (const name of names) {
|
|
163
|
-
const dir = join(parent, name)
|
|
164
|
-
if (!isPackDir(dir)) continue
|
|
165
|
-
addPack(dir, name, source)
|
|
166
|
-
let subs
|
|
167
|
-
try { subs = readdirSync(dir) } catch { continue }
|
|
168
|
-
for (const sub of subs) {
|
|
169
|
-
const subdir = join(dir, sub)
|
|
170
|
-
if (!isPackDir(subdir)) continue
|
|
171
|
-
addPack(subdir, sub, source)
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
addFrom(bundledPacksDir(), 'bundled')
|
|
176
|
-
addFrom(packsDir, 'user')
|
|
177
|
-
return [...byId.values()]
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
/** 设置 packId > memeRoot > patch config > 内置默认。 */
|
|
181
|
-
export function resolveActiveRoot(settings = {}, configRoot) {
|
|
182
|
-
const packs = scanPacks(settings.packsDir || defaultPacksDir())
|
|
183
|
-
const packId = String(settings.packId || '').trim()
|
|
184
|
-
if (packId && packId !== '_custom') {
|
|
185
|
-
const hit = packs.find((p) => p.id === packId)
|
|
186
|
-
if (hit) return hit.path
|
|
187
|
-
}
|
|
188
|
-
// 记住的 memeRoot 可能已经不存在了(比如内置包在升级后被移除/用户删掉了图库目录)。
|
|
189
|
-
// 这里只认真正有 index.db 的目录,否则一路回落到内置默认包——历史教训:把死路径
|
|
190
|
-
// 传给 MemesStore 会抛错,调用方 return,整个插件都装不起来。
|
|
191
|
-
if (settings.memeRoot && isPackDir(settings.memeRoot)) return settings.memeRoot
|
|
192
|
-
if (configRoot && isPackDir(configRoot)) return configRoot
|
|
193
|
-
return defaultMemeRoot()
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
/** 热切换时工具闭包仍指向同一对象:replace 内部 store。 */
|
|
197
|
-
export function liveStore(store) {
|
|
198
|
-
const box = {
|
|
199
|
-
get root() { return box._s.root },
|
|
200
|
-
list(...a) { return box._s.list(...a) },
|
|
201
|
-
search(...a) { return box._s.search(...a) },
|
|
202
|
-
sampleMood(...a) { return box._s.sampleMood(...a) },
|
|
203
|
-
resolveStored(...a) { return box._s.resolveStored(...a) },
|
|
204
|
-
/** 写库之后刷新内存索引快照(store 内部已关闭连接,不再有长期句柄,#43)。 */
|
|
205
|
-
refresh() { if (typeof box._s.refresh === 'function') box._s.refresh() },
|
|
206
|
-
replace(next) {
|
|
207
|
-
const prev = box._s
|
|
208
|
-
box._s = next
|
|
209
|
-
if (prev && prev !== next && typeof prev.close === 'function') prev.close()
|
|
210
|
-
},
|
|
211
|
-
}
|
|
212
|
-
box._s = store
|
|
213
|
-
return box
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
/** 模型只认这 6 个情绪桶;磁盘上仍是细 tag(路径不改)。 */
|
|
217
|
-
const MOODS = {
|
|
218
|
-
happy: ['happy', 'like', 'meow', 'givemoney', 'color'],
|
|
219
|
-
angry: ['angry', 'fool', 'baka'],
|
|
220
|
-
sad: ['sad', 'sigh'],
|
|
221
|
-
shy: ['shy'],
|
|
222
|
-
confused: ['confused', 'surprised', 'see'],
|
|
223
|
-
daily: ['daily', 'sleep', 'morning', 'work', 'cpu', 'reply'],
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
const MOOD_WORDS = {
|
|
227
|
-
happy: '开心 高兴 兴奋 喜欢 卖萌 可爱 比心 哈哈 欢迎 得意 好耶 满意',
|
|
228
|
-
angry: '生气 愤怒 暴躁 笨蛋 傻瓜 嫌弃 逮',
|
|
229
|
-
sad: '难过 哭 委屈 叹气 无语 求饶 怂 晕',
|
|
230
|
-
shy: '害羞 腼腆 脸红 花痴',
|
|
231
|
-
confused: '困惑 疑惑 惊讶 问号 懵 惊吓 震惊',
|
|
232
|
-
daily: '困 睡觉 早上好 打招呼 你好 上班 下班 摸鱼 工作 熬夜 吃饭 干饭 饿 日常',
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
export function moodNames() {
|
|
236
|
-
return Object.keys(MOODS)
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
function fineTagsFor(tag) {
|
|
240
|
-
const t = String(tag || '').trim().toLowerCase()
|
|
241
|
-
if (!t) return null
|
|
242
|
-
if (MOODS[t]) return MOODS[t]
|
|
243
|
-
for (const fine of Object.values(MOODS)) {
|
|
244
|
-
if (fine.includes(t)) return [t]
|
|
245
|
-
}
|
|
246
|
-
return [t]
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
const MOOD_DICT =
|
|
250
|
-
'happy 开心(卖萌/可爱/喜欢) / angry 生气 / sad 难过(无语/求饶) / shy 害羞 / confused 困惑惊讶 / daily 日常(睡觉/上班/早上好)'
|
|
251
|
-
|
|
252
|
-
function moodsFromQuery(text) {
|
|
253
|
-
const hit = []
|
|
254
|
-
for (const [mood, words] of Object.entries(MOOD_WORDS)) {
|
|
255
|
-
if (words.split(/\s+/).some((w) => w && text.includes(w))) hit.push(mood)
|
|
256
|
-
}
|
|
257
|
-
return hit
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
/** tag 优先;否则用 query 里的口语词推断情绪。 */
|
|
261
|
-
export function resolveMood(tag, query) {
|
|
262
|
-
const t = String(tag || '').trim().toLowerCase()
|
|
263
|
-
if (t) {
|
|
264
|
-
if (MOODS[t]) return t
|
|
265
|
-
for (const [mood, fine] of Object.entries(MOODS)) {
|
|
266
|
-
if (fine.includes(t)) return mood
|
|
267
|
-
}
|
|
268
|
-
}
|
|
269
|
-
const q = String(query || '').trim().toLowerCase()
|
|
270
|
-
if (!q) return null
|
|
271
|
-
if (MOODS[q]) return q
|
|
272
|
-
return moodsFromQuery(q)[0] || null
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
function pickRandom(rows, n) {
|
|
276
|
-
const copy = rows.slice()
|
|
277
|
-
for (let i = copy.length - 1; i > 0; i--) {
|
|
278
|
-
const j = Math.floor(Math.random() * (i + 1))
|
|
279
|
-
const tmp = copy[i]
|
|
280
|
-
copy[i] = copy[j]
|
|
281
|
-
copy[j] = tmp
|
|
282
|
-
}
|
|
283
|
-
return copy.slice(0, n)
|
|
284
|
-
}
|
|
285
|
-
|
|
286
|
-
/** 关键词分词:空格/逗号/顿号/斜杠分隔,小写去重。中文词整词先搜,不预先切。 */
|
|
287
|
-
export function keywordTokens(query) {
|
|
288
|
-
const raw = String(query || '').trim().toLowerCase()
|
|
289
|
-
if (!raw) return []
|
|
290
|
-
return [...new Set(raw.split(/[\s,,、;;/|]+/).filter(Boolean))]
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
/** 整词全都没命中时的兜底拆词:「生气猫」→ 生气 / 气猫。 */
|
|
294
|
-
function biGrams(tokens) {
|
|
295
|
-
const out = []
|
|
296
|
-
for (const t of tokens) {
|
|
297
|
-
if (t.length < 3 || !/[\u4e00-\u9fff]/.test(t)) continue
|
|
298
|
-
for (let i = 0; i + 2 <= t.length; i++) out.push(t.slice(i, i + 2))
|
|
299
|
-
}
|
|
300
|
-
return [...new Set(out)]
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
/** keywords 的分词(与 keywordTokens 同分隔符,但保留原大小写:清洗后要原样写回) */
|
|
304
|
-
const keywordWords = (s) => String(s || '').split(/[\s,,、;;/|]+/).filter(Boolean)
|
|
305
|
-
|
|
306
|
-
/**
|
|
307
|
-
* 高频关键词清洗(issue #30 附带的建议)。
|
|
308
|
-
*
|
|
309
|
-
* 外部图库常把「角色大标签」写进每一条的 keywords:deepseek-chan 里 4 个词各出现在
|
|
310
|
-
* 1407/1407 条,搜「GPT」于是命中全库(official-001 的「表情包」占 70%、dafeiyu-001 的
|
|
311
|
-
* 「大肥鱼」占 100%,同类)。判定原则:出现在 ≥50% 条目里的词对检索零信息量 ——
|
|
312
|
-
* 比维护黑名单通用,导入时算一遍词频就行。
|
|
313
|
-
*
|
|
314
|
-
* 只在条目数 ≥ minRows 时动手:小图库里的重复词往往是真关键词
|
|
315
|
-
* (3 张猫图里的「猫」出现在 100% 条目里,但它是这张库唯一的检索入口)。
|
|
316
|
-
*
|
|
317
|
-
* @param {Array<{keywords?: string}>} rows 全部条目(只需要 keywords)
|
|
318
|
-
* @param {{threshold?: number, minRows?: number}} [opts]
|
|
319
|
-
* @returns {{total: number, drop: string[], cleaned: (string|null)[]}}
|
|
320
|
-
* drop: 被剔掉的词(小写);cleaned: 每条清洗后的 keywords,没变的条目是 null。
|
|
321
|
-
*/
|
|
322
|
-
export function pruneCommonKeywords(rows, { threshold = 0.5, minRows = 8 } = {}) {
|
|
323
|
-
const list = Array.isArray(rows) ? rows : []
|
|
324
|
-
const total = list.length
|
|
325
|
-
const none = list.map(() => null)
|
|
326
|
-
if (total < minRows) return { total, drop: [], cleaned: none }
|
|
327
|
-
const words = list.map((row) => keywordWords(row && row.keywords))
|
|
328
|
-
const counts = new Map()
|
|
329
|
-
for (const toks of words) {
|
|
330
|
-
for (const w of new Set(toks.map((t) => t.toLowerCase()))) counts.set(w, (counts.get(w) || 0) + 1)
|
|
331
|
-
}
|
|
332
|
-
// 至少有两条会命中才剔:不然「过半」在小样本里可能落到 1 条上
|
|
333
|
-
const floor = Math.max(2, Math.ceil(total * threshold))
|
|
334
|
-
const drop = [...counts].filter(([, n]) => n >= floor).map(([w]) => w)
|
|
335
|
-
if (drop.length === 0) return { total, drop: [], cleaned: none }
|
|
336
|
-
const dropSet = new Set(drop)
|
|
337
|
-
return {
|
|
338
|
-
total,
|
|
339
|
-
drop,
|
|
340
|
-
cleaned: words.map((toks) => {
|
|
341
|
-
const keep = toks.filter((w) => !dropSet.has(w.toLowerCase()))
|
|
342
|
-
return keep.length === toks.length ? null : keep.join(' ')
|
|
343
|
-
}),
|
|
344
|
-
}
|
|
345
|
-
}
|
|
346
|
-
|
|
347
|
-
/**
|
|
348
|
-
* 对已落盘的图库做一次高频关键词清洗(导入/安装流程调用)。
|
|
349
|
-
* 只改 keywords 字段,图片和其它字段都不动;这是检索质量的增强,失败不该拖垮安装,
|
|
350
|
-
* 所以调用方一律 try/catch。
|
|
351
|
-
* @returns {{drop: string[], changed: number}} 剔掉的词与改动的条目数
|
|
352
|
-
*/
|
|
353
|
-
export function prunePackKeywords(indexPath, opts) {
|
|
354
|
-
const db = new DatabaseSync(indexPath)
|
|
355
|
-
try {
|
|
356
|
-
const rows = db.prepare("SELECT rowid AS rid, COALESCE(keywords, '') AS keywords FROM memes").all()
|
|
357
|
-
const { drop, cleaned } = pruneCommonKeywords(rows, opts)
|
|
358
|
-
if (drop.length === 0) return { drop: [], changed: 0 }
|
|
359
|
-
let changed = 0
|
|
360
|
-
const update = db.prepare('UPDATE memes SET keywords = ? WHERE rowid = ?')
|
|
361
|
-
for (let i = 0; i < rows.length; i++) {
|
|
362
|
-
if (cleaned[i] === null) continue
|
|
363
|
-
update.run(cleaned[i], rows[i].rid)
|
|
364
|
-
changed++
|
|
365
|
-
}
|
|
366
|
-
return { drop, changed }
|
|
367
|
-
} finally {
|
|
368
|
-
db.close()
|
|
369
|
-
}
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
const rowHay = (row) => (
|
|
373
|
-
(row.tag || '') + ' ' + (row.caption || '') + ' ' + (row.keywords || '') + ' ' + (row.file_name || '')
|
|
374
|
-
).toLowerCase()
|
|
375
|
-
|
|
376
|
-
/**
|
|
377
|
-
* 关键词搜图(纯函数:面板/工具/跨图库合并共用)。
|
|
378
|
-
* 排序:全部关键词都命中的优先;没有全命中就取命中词数最多的那一档;
|
|
379
|
-
* 同一档内随机——同一个词反复 search 能换一批,不会每次都撞同一张。
|
|
380
|
-
* @returns {{query: string, tokens: string[], memes: object[]}}
|
|
381
|
-
*/
|
|
382
|
-
export function searchRows(rows, query, limit = 8) {
|
|
383
|
-
const tokens = keywordTokens(query)
|
|
384
|
-
if (tokens.length === 0) return { query: '', tokens: [], memes: [] }
|
|
385
|
-
const scan = (words) => {
|
|
386
|
-
const hits = []
|
|
387
|
-
for (const row of rows) {
|
|
388
|
-
const hay = rowHay(row)
|
|
389
|
-
let score = 0
|
|
390
|
-
for (const w of words) if (hay.includes(w)) score++
|
|
391
|
-
if (score > 0) hits.push({ row, score })
|
|
392
|
-
}
|
|
393
|
-
return hits
|
|
394
|
-
}
|
|
395
|
-
let hits = scan(tokens)
|
|
396
|
-
if (hits.length === 0) {
|
|
397
|
-
const grams = biGrams(tokens)
|
|
398
|
-
if (grams.length) hits = scan(grams)
|
|
399
|
-
}
|
|
400
|
-
if (hits.length === 0) return { query: tokens.join(' '), tokens, memes: [] }
|
|
401
|
-
const best = Math.max(...hits.map((h) => h.score))
|
|
402
|
-
return {
|
|
403
|
-
query: tokens.join(' '),
|
|
404
|
-
tokens,
|
|
405
|
-
memes: pickRandom(hits.filter((h) => h.score === best).map((h) => h.row), limit),
|
|
406
|
-
}
|
|
407
|
-
}
|
|
408
|
-
|
|
409
|
-
/** 图库索引的读取语句(内存快照和一次性读取共用)。 */
|
|
410
|
-
const SELECT_ROWS = 'SELECT path, tag, file_name, caption, COALESCE(keywords, \'\') AS keywords FROM memes'
|
|
411
|
-
|
|
412
|
-
/**
|
|
413
|
-
* 图库索引(只读检索)。
|
|
414
|
-
*
|
|
415
|
-
* issue #43:以前这里在构造时打开 SQLite 连接并**一直持有**。插件默认激活内置图库
|
|
416
|
-
* (`<插件包>/memes/dafeiyu-001`),它就在 npm 包目录里;Windows 上只要目录里还有
|
|
417
|
-
* 打开的文件,`rename` 该目录就会 EPERM/EBUSY,而插件市场更新正是用 pnpm 把
|
|
418
|
-
* `node_modules/dsh-meme` 整个目录改名替换 → 更新失败(`ERR_PNPM_EPERM ... rename`)。
|
|
419
|
-
* 现在构造时一次性把索引读进内存并立刻关掉连接;写操作由 openIndexWriter 落盘后
|
|
420
|
-
* 调 refresh() 刷新快照。索引只有几千行(947K 的图库,索引本身几百 KB),
|
|
421
|
-
* 常驻内存的代价可以忽略,换来的好处是插件运行期**不占用图库文件**。
|
|
422
|
-
*/
|
|
423
|
-
export class MemesStore {
|
|
424
|
-
constructor(root = defaultMemeRoot()) {
|
|
425
|
-
this.root = resolve(root)
|
|
426
|
-
if (!existsSync(join(this.root, 'index.db'))) {
|
|
427
|
-
throw new Error('缺少表情包索引: ' + join(this.root, 'index.db'))
|
|
428
|
-
}
|
|
429
|
-
this.rows = this.readRows()
|
|
430
|
-
}
|
|
431
|
-
|
|
432
|
-
/** 一次性读全表并关闭连接(不在磁盘上留长连接)。 */
|
|
433
|
-
readRows() {
|
|
434
|
-
const db = new DatabaseSync(join(this.root, 'index.db'), { readOnly: true })
|
|
435
|
-
try {
|
|
436
|
-
return db.prepare(SELECT_ROWS).all()
|
|
437
|
-
} finally {
|
|
438
|
-
try { db.close() } catch { /* 已关闭 */ }
|
|
439
|
-
}
|
|
440
|
-
}
|
|
441
|
-
|
|
442
|
-
/** 写操作(openIndexWriter)落盘后刷新内存快照,否则校验/搜图还看到旧数据。 */
|
|
443
|
-
refresh() {
|
|
444
|
-
this.rows = this.readRows()
|
|
445
|
-
}
|
|
446
|
-
|
|
447
|
-
/**
|
|
448
|
-
* 列表情包:tag 为情绪桶或细分类;query 只做 caption/keywords 子串(管理面板用)。
|
|
449
|
-
* exact = true 时按 tag 精确匹配、不做情绪桶展开——管理面板的分类下拉列的是
|
|
450
|
-
* 图库里真实的 tag,选「开心」却混进 like/meow 的桶展开行为会把用户搞糊涂(用户反馈)。
|
|
451
|
-
*/
|
|
452
|
-
list(tag, query, exact = false) {
|
|
453
|
-
const rows = this.rows
|
|
454
|
-
const tags = moodNames()
|
|
455
|
-
let memes = rows
|
|
456
|
-
if (exact && tag) {
|
|
457
|
-
memes = memes.filter((m) => m.tag === String(tag).trim().toLowerCase())
|
|
458
|
-
} else {
|
|
459
|
-
const fine = fineTagsFor(tag)
|
|
460
|
-
if (fine) memes = memes.filter((m) => fine.includes(m.tag))
|
|
461
|
-
}
|
|
462
|
-
const q = query && String(query).trim().toLowerCase()
|
|
463
|
-
if (q) {
|
|
464
|
-
const tokens = q.split(/\s+/).filter(Boolean)
|
|
465
|
-
memes = memes.filter((m) => {
|
|
466
|
-
const hay = (m.tag + ' ' + (m.caption ?? '') + ' ' + (m.keywords ?? '')).toLowerCase()
|
|
467
|
-
return tokens.some((t) => hay.includes(t))
|
|
468
|
-
})
|
|
469
|
-
}
|
|
470
|
-
return { memes, tags }
|
|
471
|
-
}
|
|
472
|
-
|
|
473
|
-
/**
|
|
474
|
-
* 关键词搜图。给了 tag 就先把范围限在那个情绪桶里(细 tag 展开同 list),
|
|
475
|
-
* 于是「情绪 + 关键词」= 在桶里筛词。
|
|
476
|
-
* @returns {{query: string, tokens: string[], memes: object[], tags: string[]}}
|
|
477
|
-
*/
|
|
478
|
-
search(query, n = 8, tag = null) {
|
|
479
|
-
const rows = this.rows
|
|
480
|
-
const fine = fineTagsFor(tag)
|
|
481
|
-
const scoped = fine ? rows.filter((m) => fine.includes(m.tag)) : rows
|
|
482
|
-
return { ...searchRows(scoped, query, n), tags: moodNames() }
|
|
483
|
-
}
|
|
484
|
-
|
|
485
|
-
/** 按情绪取池,随机抽 n 张给模型看 caption。 */
|
|
486
|
-
sampleMood(tag, query, n = 5) {
|
|
487
|
-
const mood = resolveMood(tag, query)
|
|
488
|
-
if (!mood) return { mood: null, memes: [], tags: moodNames() }
|
|
489
|
-
const { memes } = this.list(mood)
|
|
490
|
-
return { mood, memes: pickRandom(memes, n), tags: moodNames() }
|
|
491
|
-
}
|
|
492
|
-
|
|
493
|
-
/** 把索引内相对路径解析为绝对路径(不允许逃出图库根)。 */
|
|
494
|
-
resolveStored(stored) {
|
|
495
|
-
const target = resolve(this.root, stored)
|
|
496
|
-
if (target !== this.root && !target.startsWith(this.root + sep)) {
|
|
497
|
-
throw new Error('路径超出表情包目录')
|
|
498
|
-
}
|
|
499
|
-
if (!existsSync(target)) {
|
|
500
|
-
throw new Error('文件不存在: ' + stored)
|
|
501
|
-
}
|
|
502
|
-
return target
|
|
503
|
-
}
|
|
504
|
-
|
|
505
|
-
/** 接口保留:连接已在构造时关闭,热切换时调用 close() 不需要额外动作。 */
|
|
506
|
-
close() {}
|
|
507
|
-
}
|
|
508
|
-
|
|
509
|
-
/**
|
|
510
|
-
* 图库索引的**可写**连接(管理 API 上传/删除、learn_meme 学图用)。
|
|
511
|
-
*
|
|
512
|
-
* 用户图库(~/.dsh/meme-packs)保持常驻连接,和以前一样省去每次开关库的开销。
|
|
513
|
-
* 插件包内的图库则绝不常驻:更新时 pnpm 要 rename 整个包目录,Windows 上目录里
|
|
514
|
-
* 只要有打开的文件就会 EPERM(#43)。这类目录改成每条语句临时 open→执行→close,
|
|
515
|
-
* 写完立刻释放;对调用方暴露的 prepare/exec/close 接口保持不变。
|
|
516
|
-
*
|
|
517
|
-
* @param {string} root 图库根目录
|
|
518
|
-
* @param {{packageDir?: string}} [opts] packageDir 供测试指定「插件包根」,默认按本模块位置推
|
|
519
|
-
*/
|
|
520
|
-
export function openIndexWriter(root, opts = {}) {
|
|
521
|
-
const dir = resolve(root)
|
|
522
|
-
const indexPath = join(dir, 'index.db')
|
|
523
|
-
// 用户图库(包外):维持常驻可写连接。
|
|
524
|
-
if (!isInsidePluginPackage(dir, opts.packageDir)) {
|
|
525
|
-
const db = new DatabaseSync(indexPath)
|
|
526
|
-
return {
|
|
527
|
-
prepare: (...args) => db.prepare(...args),
|
|
528
|
-
exec: (...args) => db.exec(...args),
|
|
529
|
-
close: () => { try { db.close() } catch { /* 已关闭 */ } },
|
|
530
|
-
}
|
|
531
|
-
}
|
|
532
|
-
// 插件包内:每条语句开、关一次,插件运行期不占包内文件。
|
|
533
|
-
const withDb = (fn) => {
|
|
534
|
-
const db = new DatabaseSync(indexPath)
|
|
535
|
-
try {
|
|
536
|
-
return fn(db)
|
|
537
|
-
} finally {
|
|
538
|
-
try { db.close() } catch { /* 已关闭 */ }
|
|
539
|
-
}
|
|
540
|
-
}
|
|
541
|
-
const statement = (sql) => ({
|
|
542
|
-
run: (...args) => withDb((db) => db.prepare(sql).run(...args)),
|
|
543
|
-
get: (...args) => withDb((db) => db.prepare(sql).get(...args)),
|
|
544
|
-
all: (...args) => withDb((db) => db.prepare(sql).all(...args)),
|
|
545
|
-
})
|
|
546
|
-
return {
|
|
547
|
-
prepare: statement,
|
|
548
|
-
exec: (sql) => withDb((db) => db.exec(sql)),
|
|
549
|
-
close: () => { /* 无常驻连接 */ },
|
|
550
|
-
}
|
|
551
|
-
}
|
|
552
|
-
|
|
553
|
-
/**
|
|
554
|
-
* 已知 IM 渠道的 id(rpcId 前缀)。与 @xmanrui/dsh-im 的 channel 列表保持一致:
|
|
555
|
-
* 它给每条进来的消息写 `source.rpcId = <channel>-<uuid>`(steer 消息是
|
|
556
|
-
* `<channel>-steer-<uuid>`),旧版还会把 `<channel>-` 直接拼进会话 id。
|
|
557
|
-
* dsh-im 将来加渠道时在这里补一项即可,没列到的渠道会退回 Web 的标记模式。
|
|
558
|
-
*/
|
|
559
|
-
export const IM_CHANNEL_PREFIXES = Object.freeze([
|
|
560
|
-
'weixin', 'feishu', 'dingtalk', 'wecom', 'wecomapp', 'qq', 'slack', 'telegram',
|
|
561
|
-
'discord', 'whatsapp', 'imessage', 'matrix', 'email', 'office',
|
|
562
|
-
])
|
|
563
|
-
|
|
564
|
-
/** IM 渠道 id → 展示名(写进提示词/工具结果,让模型知道当前是哪个聊天软件)。 */
|
|
565
|
-
export const IM_CHANNEL_LABELS = Object.freeze({
|
|
566
|
-
weixin: '微信',
|
|
567
|
-
feishu: '飞书',
|
|
568
|
-
dingtalk: '钉钉',
|
|
569
|
-
wecom: '企业微信',
|
|
570
|
-
wecomapp: '企业微信应用',
|
|
571
|
-
qq: 'QQ',
|
|
572
|
-
slack: 'Slack',
|
|
573
|
-
telegram: 'Telegram',
|
|
574
|
-
discord: 'Discord',
|
|
575
|
-
whatsapp: 'WhatsApp',
|
|
576
|
-
imessage: 'iMessage',
|
|
577
|
-
matrix: 'Matrix',
|
|
578
|
-
email: '邮件',
|
|
579
|
-
office: 'AI Office',
|
|
580
|
-
})
|
|
581
|
-
|
|
582
|
-
const IM_UUID_PATTERN = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'
|
|
583
|
-
const IM_RPC_ID_RE = new RegExp('^(' + IM_CHANNEL_PREFIXES.join('|') + ')-(?:steer-)?' + IM_UUID_PATTERN + '$', 'u')
|
|
584
|
-
const IM_LEGACY_SESSION_ID_RE = new RegExp('^(' + IM_CHANNEL_PREFIXES.join('|') + ')-.+', 'u')
|
|
585
|
-
|
|
586
|
-
function sessionEventsOf(session) {
|
|
587
|
-
const events = typeof session?.snapshotEvents === 'function'
|
|
588
|
-
? session.snapshotEvents()
|
|
589
|
-
: session?.events
|
|
590
|
-
return Array.isArray(events) ? events : []
|
|
591
|
-
}
|
|
592
|
-
|
|
593
|
-
/**
|
|
594
|
-
* 这个会话当前这一轮是不是从 IM(dsh-im 的 QQ/微信/飞书…)进来的,是则返回渠道 id。
|
|
595
|
-
*
|
|
596
|
-
* 判据取「最后一条真实用户消息」的 rpcId 前缀,而不是扫全会话:同一个会话
|
|
597
|
-
* 可以在 Web 里创建、后来被 dsh-im 用 `/session` 绑到某个 IM 聊天(会话同步),
|
|
598
|
-
* 那样早先的 Web 消息和后来的 IM 消息会混在同一段日志里——机器人在哪个渠道
|
|
599
|
-
* 回复,取决于这一轮是从哪进来的。Web UI 的 rpcId 是没有渠道前缀的裸 uuid,
|
|
600
|
-
* 于是自然不命中。
|
|
601
|
-
*
|
|
602
|
-
* fork 出来的会话不能继承父会话的渠道(父子消息会混在事件流里),宿主两版
|
|
603
|
-
* Session 都暴露 inheritedEventCount,拿不到就不猜。
|
|
604
|
-
*/
|
|
605
|
-
export function imChannelOfSession(session) {
|
|
606
|
-
if (!session || typeof session !== 'object') return null
|
|
607
|
-
try {
|
|
608
|
-
const header = session.header && typeof session.header === 'object' ? session.header : null
|
|
609
|
-
const inherited = session.inheritedEventCount
|
|
610
|
-
if (header?.parentSession && !Number.isSafeInteger(inherited)) return null
|
|
611
|
-
const events = sessionEventsOf(session)
|
|
612
|
-
for (let i = events.length - 1; i >= 0; i--) {
|
|
613
|
-
const event = events[i]
|
|
614
|
-
if (!event || event.type !== 'user/message') continue
|
|
615
|
-
if (Number.isSafeInteger(inherited) && Number.isSafeInteger(event.seq) && event.seq < inherited) continue
|
|
616
|
-
const source = event.data && event.data.source
|
|
617
|
-
if (!source || source.kind !== 'user') continue
|
|
618
|
-
const rpcId = String(source.rpcId || '')
|
|
619
|
-
if (!rpcId) continue
|
|
620
|
-
const hit = IM_RPC_ID_RE.exec(rpcId)
|
|
621
|
-
if (hit) return hit[1]
|
|
622
|
-
// 最近一条用户消息有 rpcId、但没命中 IM 前缀:这一轮来自 Web/其他来源
|
|
623
|
-
return null
|
|
624
|
-
}
|
|
625
|
-
if (header?.parentSession) return null
|
|
626
|
-
// 旧版 dsh-im 把渠道写进会话 id;新版 id 是纯 uuid,只能靠上面的 rpcId
|
|
627
|
-
const id = typeof session.id === 'string'
|
|
628
|
-
? session.id
|
|
629
|
-
: typeof session.sessionId === 'string' ? session.sessionId : ''
|
|
630
|
-
const legacy = IM_LEGACY_SESSION_ID_RE.exec(id)
|
|
631
|
-
return legacy ? legacy[1] : null
|
|
632
|
-
} catch {
|
|
633
|
-
// 宿主会话对象处于半初始化/已释放状态时不能连累系统提示装配
|
|
634
|
-
return null
|
|
635
|
-
}
|
|
636
|
-
}
|
|
637
|
-
|
|
638
|
-
/**
|
|
639
|
-
* AI 的发送方式(设置页「发送方式」下拉框):
|
|
640
|
-
* - auto(默认):按渠道自动——Web 写 [表情: 描述] 由前端配图,IM 会话改走 dsh_im_return_file;
|
|
641
|
-
* - text:纯文字,不发表情图片(仍可查候选,但只用文字描述/接梗);
|
|
642
|
-
* - image:总是发图——Web 写标记,IM 必须调 dsh_im_return_file。
|
|
643
|
-
* 只影响 AI 怎么发,不改前端把 [表情: 描述] 配成图的渲染逻辑。
|
|
644
|
-
*/
|
|
645
|
-
export const SEND_MODES = ['auto', 'text', 'image']
|
|
646
|
-
export function normalizeSendMode(value) {
|
|
647
|
-
return SEND_MODES.includes(value) ? value : 'auto'
|
|
648
|
-
}
|
|
649
|
-
|
|
650
|
-
/**
|
|
651
|
-
* 表情排布方式(设置页「表情排布」下拉框,issue #50):
|
|
652
|
-
* - inline(默认):图与正文并排——图提到消息行行首,正文在右,短消息紧凑;
|
|
653
|
-
* - stacked:图独占一行在上,正文按正常宽度铺开在下,阅读宽度完整。
|
|
654
|
-
* 只影响前端把 [表情: 描述] 渲染成图后的排布,默认保持并排不改已有用户观感。
|
|
655
|
-
*/
|
|
656
|
-
export const LAYOUT_MODES = ['inline', 'stacked']
|
|
657
|
-
export function normalizeLayoutMode(value) {
|
|
658
|
-
return LAYOUT_MODES.includes(value) ? value : 'inline'
|
|
659
|
-
}
|
|
660
|
-
|
|
661
|
-
// ---- 用户收藏的稳定落点与图库目录扫描 ----
|
|
662
|
-
|
|
663
|
-
/** 扫描/收录认可的图片扩展(与上传、AI 学图一致) */
|
|
664
|
-
export const SCAN_IMAGE_EXTS = ['.jpg', '.jpeg', '.png', '.gif', '.webp']
|
|
665
|
-
|
|
666
|
-
const SCAN_TAG_RE = /^[a-z0-9_-]+$/
|
|
667
|
-
|
|
668
|
-
/**
|
|
669
|
-
* 手动放进图库目录的图片 → 索引行(扫描入库用,纯函数便于单测)。
|
|
670
|
-
* 分类取路径首段目录名(memes/<tag>/x.jpg → <tag>,<tag>/x.jpg → <tag>);
|
|
671
|
-
* 首段不是合法 tag、或图片散在根目录 → misc。path 保持磁盘上的真实相对路径
|
|
672
|
-
* (图片路由按索引 path 找文件,不能为了格式好看改写)。描述兜底用文件名去扩展名。
|
|
673
|
-
*/
|
|
674
|
-
export function scanRowFor(rel) {
|
|
675
|
-
const posix = String(rel || '').replace(/\\/g, '/').replace(/^\/+/, '')
|
|
676
|
-
const body = posix.startsWith('memes/') ? posix.slice('memes/'.length) : posix
|
|
677
|
-
const segs = body.split('/').filter(Boolean)
|
|
678
|
-
const file = segs[segs.length - 1] || ''
|
|
679
|
-
const tag = segs.length >= 2 && SCAN_TAG_RE.test(segs[0]) ? segs[0] : 'misc'
|
|
680
|
-
const dot = file.lastIndexOf('.')
|
|
681
|
-
const stem = dot > 0 ? file.slice(0, dot) : file
|
|
682
|
-
return { path: posix, tag, file_name: file, caption: stem.slice(0, 200) }
|
|
683
|
-
}
|
|
684
|
-
|
|
685
|
-
/**
|
|
686
|
-
* 递归列出图库目录下的图片文件(相对 root 的 posix 路径),跳过 index.db、
|
|
687
|
-
* manifest.json 与隐藏目录。用户「自己塞进文件夹」的图从这里入库:原始字节
|
|
688
|
-
* 原样保留——聊天附件通道会把 GIF 压成单帧,磁盘文件不会。
|
|
689
|
-
*/
|
|
690
|
-
export function walkPackImages(root) {
|
|
691
|
-
const out = []
|
|
692
|
-
const walk = (dir, prefix) => {
|
|
693
|
-
let entries = []
|
|
694
|
-
try { entries = readdirSync(dir, { withFileTypes: true }) } catch { return }
|
|
695
|
-
for (const e of entries) {
|
|
696
|
-
if (e.name.startsWith('.') || e.name === 'manifest.json' || e.name.startsWith('index.db')) continue
|
|
697
|
-
const abs = join(dir, e.name)
|
|
698
|
-
const rel = prefix ? prefix + '/' + e.name : e.name
|
|
699
|
-
if (e.isDirectory()) { walk(abs, rel); continue }
|
|
700
|
-
if (!e.isFile()) continue
|
|
701
|
-
const dot = e.name.lastIndexOf('.')
|
|
702
|
-
const ext = dot >= 0 ? e.name.slice(dot).toLowerCase() : ''
|
|
703
|
-
if (SCAN_IMAGE_EXTS.includes(ext)) out.push(rel)
|
|
704
|
-
}
|
|
705
|
-
}
|
|
706
|
-
walk(resolve(root), '')
|
|
707
|
-
return out.sort()
|
|
708
|
-
}
|
|
709
|
-
|
|
710
|
-
/**
|
|
711
|
-
* 确保一个最小图库存在于 dir(manifest.json + 空 index.db),已存在则不动。
|
|
712
|
-
* 给「我的收藏」这类程序化创建的稳定图库用。
|
|
713
|
-
*/
|
|
714
|
-
export function ensurePackAt(dir, meta) {
|
|
715
|
-
mkdirSync(dir, { recursive: true })
|
|
716
|
-
const indexPath = join(dir, 'index.db')
|
|
717
|
-
if (!existsSync(indexPath)) {
|
|
718
|
-
const db = new DatabaseSync(indexPath)
|
|
719
|
-
db.exec('CREATE TABLE IF NOT EXISTS memes (path TEXT PRIMARY KEY, tag TEXT, file_name TEXT, caption TEXT, keywords TEXT, mtime REAL, captioned_at REAL)')
|
|
720
|
-
db.close()
|
|
721
|
-
}
|
|
722
|
-
const manifestPath = join(dir, 'manifest.json')
|
|
723
|
-
if (!existsSync(manifestPath)) {
|
|
724
|
-
writeFileSync(manifestPath, JSON.stringify({ id: meta.id, name: meta.name, description: String(meta.description || ''), version: '1.0.0' }, null, 2))
|
|
725
|
-
}
|
|
726
|
-
return dir
|
|
727
|
-
}
|
|
728
|
-
|
|
729
|
-
/**
|
|
730
|
-
* 把 src 图库里的指定条目(索引行 + 文件)搬到 dst 图库的 memes/<tag>/ 下,保持分类。
|
|
731
|
-
* 用于把内置图库里用户后加的收藏搬去包外的稳定图库——插件升级会整个替换包目录,
|
|
732
|
-
* 留在里面的用户文件会被清掉。目标撞名时加时间缀;rename 跨盘失败回落 copy+unlink。
|
|
733
|
-
* 返回 { moved: [{from,to}], missing: [...] }(missing = 索引行或文件已不存在)。
|
|
734
|
-
*/
|
|
735
|
-
export function movePackEntries(srcRoot, dstRoot, paths) {
|
|
736
|
-
const moved = []
|
|
737
|
-
const missing = []
|
|
738
|
-
const src = openIndexWriter(srcRoot)
|
|
739
|
-
const dst = openIndexWriter(dstRoot)
|
|
740
|
-
try {
|
|
741
|
-
for (const rel of paths || []) {
|
|
742
|
-
const row = src.prepare('SELECT tag, file_name, caption, keywords FROM memes WHERE path = ?').get(String(rel))
|
|
743
|
-
const from = join(resolve(srcRoot), String(rel))
|
|
744
|
-
if (!row || !existsSync(from)) { missing.push(String(rel)); continue }
|
|
745
|
-
const tag = SCAN_TAG_RE.test(String(row.tag || '')) ? row.tag : 'misc'
|
|
746
|
-
let name = basename(String(rel))
|
|
747
|
-
let toRel = 'memes/' + tag + '/' + name
|
|
748
|
-
if (existsSync(join(resolve(dstRoot), toRel))) {
|
|
749
|
-
const dot = name.lastIndexOf('.')
|
|
750
|
-
name = (dot > 0 ? name.slice(0, dot) : name) + '_' + Date.now() + (dot > 0 ? name.slice(dot) : '')
|
|
751
|
-
toRel = 'memes/' + tag + '/' + name
|
|
752
|
-
}
|
|
753
|
-
const to = join(resolve(dstRoot), toRel)
|
|
754
|
-
mkdirSync(dirname(to), { recursive: true })
|
|
755
|
-
try { renameSync(from, to) } catch {
|
|
756
|
-
copyFileSync(from, to)
|
|
757
|
-
unlinkSync(from)
|
|
758
|
-
}
|
|
759
|
-
dst.prepare('INSERT OR REPLACE INTO memes (path, tag, file_name, caption, keywords, mtime, captioned_at) VALUES (?, ?, ?, ?, ?, ?, ?)')
|
|
760
|
-
.run(toRel, tag, name, row.caption || '', row.keywords || '', Date.now(), Date.now())
|
|
761
|
-
src.prepare('DELETE FROM memes WHERE path = ?').run(String(rel))
|
|
762
|
-
moved.push({ from: String(rel), to: toRel })
|
|
763
|
-
}
|
|
764
|
-
} finally {
|
|
765
|
-
try { src.close() } catch { /* 已关闭 */ }
|
|
766
|
-
try { dst.close() } catch { /* 已关闭 */ }
|
|
767
|
-
}
|
|
768
|
-
return { moved, missing }
|
|
769
|
-
}
|
|
770
|
-
|
|
771
|
-
/**
|
|
772
|
-
* 注册 send_meme 工具。
|
|
773
|
-
*
|
|
774
|
-
* 三种模式:
|
|
775
|
-
* - Web 模式(无 QQ 通道,有 urlPrefix):只保留 search——随机抽候选,
|
|
776
|
-
* 模型挑一张把 [表情: 描述] 写进回复,前端按描述配图,
|
|
777
|
-
* 不需要冗余的 send 动作;
|
|
778
|
-
* - IM 模式(Web 模式 + 本轮来自 dsh-im 的 QQ/微信等渠道):候选额外带绝对路径,
|
|
779
|
-
* IM 聊天不渲染 [表情: 描述] 标记,模型要把挑中的 path 交给 dsh-im 的
|
|
780
|
-
* `dsh_im_return_file` 作为原生图片发出;
|
|
781
|
-
* - QQ 模式(companionQq 可用):两步式,action=send 才是真正的投递动作。
|
|
782
|
-
*
|
|
783
|
-
* @param {object} ctx 插件上下文
|
|
784
|
-
* @param {MemesStore} memes 图库
|
|
785
|
-
* @param {(path: string, caption?: string) => void | null} sendImage QQ 通道发送
|
|
786
|
-
* (dsh-companion 的 companionQq.sendImage);传 null 时走 web 模式。
|
|
787
|
-
* @param {string | null} urlPrefix webServer 图片路由前缀(如 '/dsh-memes'),无则 null
|
|
788
|
-
* @param {object} [options]
|
|
789
|
-
* @param {(session: object) => string | null} [options.imChannelOf]
|
|
790
|
-
* 判断某个会话本轮来自哪个 IM 渠道(dsh-im 可用时由 index.js 传入;返回 null = 非 IM 或能力缺失)
|
|
791
|
-
* @param {boolean} [options.imReady] 注册时 dsh-im 是否已在进程内(只影响工具描述措辞)
|
|
792
|
-
* @param {() => string} [options.sendMode] 运行时读发送方式设置(auto/text/image)
|
|
793
|
-
* @param {() => Array<{tag: string, count: number}> | null} [options.tagStats]
|
|
794
|
-
* 跨启用图库的分类统计(按张数降序)。搜索没命中时用它给模型真实的换词建议,
|
|
795
|
-
* 而不是只甩一串静态情绪字典(issue #53)。
|
|
796
|
-
*/
|
|
797
|
-
function clampLimit(n) {
|
|
798
|
-
const x = typeof n === 'number' ? n : Number(n)
|
|
799
|
-
if (!Number.isFinite(x)) return 8
|
|
800
|
-
return Math.max(1, Math.min(20, Math.floor(x)))
|
|
801
|
-
}
|
|
802
|
-
|
|
803
|
-
export function registerSendMemeTool(ctx, memes, sendImage, urlPrefix = null, options = {}) {
|
|
804
|
-
const webMode = !sendImage && !!urlPrefix
|
|
805
|
-
const imChannelOf = typeof options.imChannelOf === 'function' ? options.imChannelOf : null
|
|
806
|
-
/** 注册时 dsh-im 是否已在进程内——只决定工具描述要不要提 IM 的发送方式 */
|
|
807
|
-
const imReady = options.imReady === true
|
|
808
|
-
/** 运行时的发送方式设置(auto/text/image):每次执行读一次,设置改了下一条消息就生效 */
|
|
809
|
-
const sendModeOf = typeof options.sendMode === 'function' ? options.sendMode : () => 'auto'
|
|
810
|
-
/** 跨启用图库的分类统计(张数降序);没有就退回静态情绪字典 */
|
|
811
|
-
const tagStatsOf = typeof options.tagStats === 'function' ? options.tagStats : () => null
|
|
812
|
-
/** 没命中时给模型的换词建议:真实分类统计优先,拉不到才用静态情绪字典(issue #53) */
|
|
813
|
-
const tagHint = () => {
|
|
814
|
-
try {
|
|
815
|
-
const stats = tagStatsOf()
|
|
816
|
-
if (Array.isArray(stats) && stats.length > 0) {
|
|
817
|
-
const top = stats.slice(0, 15).map((s) => s.tag + '(' + s.count + ')').join(' / ')
|
|
818
|
-
return '当前启用图库里的分类(按张数): ' + top
|
|
819
|
-
}
|
|
820
|
-
} catch { /* 统计失败退回字典 */ }
|
|
821
|
-
return '情绪字典: ' + MOOD_DICT
|
|
822
|
-
}
|
|
823
|
-
|
|
824
|
-
const parameters = {
|
|
825
|
-
tag: {
|
|
826
|
-
type: 'string',
|
|
827
|
-
description: '情绪范围(可选): ' + MOOD_DICT + '。只给 tag = 在该情绪里随机抽;tag + query = 在该情绪里按关键词筛。',
|
|
828
|
-
},
|
|
829
|
-
query: {
|
|
830
|
-
type: 'string',
|
|
831
|
-
description: '关键词(可选,想找特定的图就用它): 按 caption/关键词/图名子串搜,比只抽情绪准。中文词,空格分隔多个(如「猫」「生气 猫」「无语」);整词没命中会自动拆词重试。没给 tag 时,搜不到也会拿它推断情绪。',
|
|
832
|
-
},
|
|
833
|
-
limit: {
|
|
834
|
-
type: 'number',
|
|
835
|
-
description: '本次返回几张候选(1-20,默认 8)。拿不准就多抽点;不满意再 search 换一批。',
|
|
836
|
-
},
|
|
837
|
-
}
|
|
838
|
-
if (!webMode) {
|
|
839
|
-
parameters.action = {
|
|
840
|
-
type: 'string',
|
|
841
|
-
enum: ['search', 'send'],
|
|
842
|
-
description: 'search: 按情绪或关键词取候选; send: 发送挑中的 path',
|
|
843
|
-
}
|
|
844
|
-
parameters.path = { type: 'string', description: 'send 时要发的图路径(来自 search 候选列表)' }
|
|
845
|
-
}
|
|
846
|
-
|
|
847
|
-
ctx.tools.register(defineTool({
|
|
848
|
-
name: 'send_meme',
|
|
849
|
-
description: '发一张表情包。两种搜法:①只给 tag(情绪)→ 从该情绪里随机抽;②给 query(关键词)→ 在 caption/关键词/图名里搜,想找特定的图(「猫」「比心」「摸鱼」)就用这个;两个都给 = 在该情绪里按关键词筛,最准。' +
|
|
850
|
-
'流程:给 tag/query → 系统返回若干张候选(带 caption,数量用 limit 自己定) → 看描述觉得贴就发;不满意再 search 换一批,还不行就换词/换情绪或回文字。' +
|
|
851
|
-
'情绪字典: ' + MOOD_DICT + '。' +
|
|
852
|
-
(webMode
|
|
853
|
-
? (imReady
|
|
854
|
-
? '发送方式看工具结果末尾的说明:Web 聊天把 [表情: 描述] 原样写进回复(描述抄候选原文,不要带网址);IM(QQ/微信等)聊天调用 dsh_im_return_file 传候选的 path 发原生图片,不要写 [表情: ...] 标记。'
|
|
855
|
-
: '挑中后把 [表情: 描述] 原样写进回复(描述必须抄候选原文,不要带网址)——自己编的描述前端配不上图。')
|
|
856
|
-
: '两步:search 看候选,再用 send + path 发出。') +
|
|
857
|
-
'发送方式以设置里的「发送方式」下拉框为准(自动/纯文字/图片),每次结果末尾的「发图」说明会告诉你怎么发。' +
|
|
858
|
-
'气氛对了就主动发;发完短接,让图自己说话。',
|
|
859
|
-
parameters,
|
|
860
|
-
output: {
|
|
861
|
-
schema: { type: 'json' },
|
|
862
|
-
render: (_args, value) => [{ type: 'text', text: value.message }],
|
|
863
|
-
},
|
|
864
|
-
execute(args, exec) {
|
|
865
|
-
const action = webMode ? 'search' : (args.action === 'send' ? 'send' : 'search')
|
|
866
|
-
const query = typeof args.query === 'string' ? args.query.trim() : ''
|
|
867
|
-
const tag = typeof args.tag === 'string' ? args.tag.trim().toLowerCase() : ''
|
|
868
|
-
const path = typeof args.path === 'string' ? args.path.trim() : ''
|
|
869
|
-
const limit = clampLimit(args.limit)
|
|
870
|
-
const sendMode = normalizeSendMode(sendModeOf())
|
|
871
|
-
const textMode = sendMode === 'text'
|
|
872
|
-
const imageMode = sendMode === 'image'
|
|
873
|
-
|
|
874
|
-
if (action === 'send') {
|
|
875
|
-
if (textMode) {
|
|
876
|
-
return { ok: false, message: '当前发送方式是「纯文字」,不发图片;直接用文字接梗/描述即可' }
|
|
877
|
-
}
|
|
878
|
-
if (!path) {
|
|
879
|
-
return { ok: false, message: 'send 需要 path——先 search 看候选,再挑一张发' }
|
|
880
|
-
}
|
|
881
|
-
let absolute
|
|
882
|
-
try {
|
|
883
|
-
absolute = memes.resolveStored(path)
|
|
884
|
-
} catch (error) {
|
|
885
|
-
return { ok: false, message: '未知路径: ' + path + ' —— 用 search 的候选 path' }
|
|
886
|
-
}
|
|
887
|
-
if (sendImage) {
|
|
888
|
-
try
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
const
|
|
907
|
-
|
|
908
|
-
const
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
(
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
1
|
+
/**
|
|
2
|
+
* 表情包存储与搜索(dsh-expression 插件)。
|
|
3
|
+
*
|
|
4
|
+
* 模型侧两种搜法:①按 6 个情绪桶选 tag,从桶里随机抽若干张;②按关键词
|
|
5
|
+
* 在 caption/关键词/图名里子串搜(全部关键词命中优先)。两个都给 = 在该
|
|
6
|
+
* 情绪里筛关键词。候选都带 caption,模型看描述觉得贴再发。
|
|
7
|
+
*/
|
|
8
|
+
import { DatabaseSync } from 'node:sqlite'
|
|
9
|
+
import { basename, dirname, join, resolve, sep } from 'node:path'
|
|
10
|
+
import { homedir } from 'node:os'
|
|
11
|
+
import { fileURLToPath } from 'node:url'
|
|
12
|
+
import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
|
|
13
|
+
import { defineTool } from '@deepseek-ai/dsh-tools'
|
|
14
|
+
|
|
15
|
+
/** 内置图库根目录:插件包内 memes/<id>/(随包分发的只有 dafeiyu-001)。 */
|
|
16
|
+
export function bundledPacksDir() {
|
|
17
|
+
return fileURLToPath(new URL('./memes', import.meta.url))
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* dsh 的 home 目录(设置/图库扫描目录的根)。
|
|
22
|
+
* 用 os.homedir() 而不是 process.env.HOME:Windows 上通常没有 HOME,
|
|
23
|
+
* 回落成 '.' 会让设置文件和扫描目录跟着 CWD 走(历史 bug:.dsh\meme-packs 变相对路径)。
|
|
24
|
+
* 测试用 DSH_MEME_HOME 覆盖到临时目录。
|
|
25
|
+
*/
|
|
26
|
+
export function dshHome() {
|
|
27
|
+
return process.env.DSH_MEME_HOME || homedir()
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** 内置默认图库根:随插件分发的 memes/dafeiyu-001(大肥鱼)。可用 memeRoot 覆盖。 */
|
|
31
|
+
export function defaultMemeRoot() {
|
|
32
|
+
return join(bundledPacksDir(), 'dafeiyu-001')
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** 用户导入/自建图库的扫描目录。 */
|
|
36
|
+
export function defaultPacksDir() {
|
|
37
|
+
return join(dshHome(), '.dsh', 'meme-packs')
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* 本插件包自己的根目录。
|
|
42
|
+
* 装成插件时就是 `node_modules/dsh-meme`;插件市场更新会用 pnpm 把整个目录改名替换。
|
|
43
|
+
* @param {string} [fromDir] 测试用:以某个目录作为「插件包根」,不传则按本模块位置推。
|
|
44
|
+
*/
|
|
45
|
+
export function pluginPackageDir(fromDir) {
|
|
46
|
+
return fromDir ? resolve(fromDir) : resolve(bundledPacksDir(), '..')
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* dir 是否落在插件包目录里。
|
|
51
|
+
*
|
|
52
|
+
* 为什么关心这件事:内置图库在 `<插件包>/memes/<id>` 里,用户在上面学图/上传时
|
|
53
|
+
* 插件会写这个目录。Windows 上目录里只要有打开的文件句柄,`rename` 该目录(或它的
|
|
54
|
+
* 祖先)就报 `EPERM`;而 pnpm 更新正是 rename 整个包目录 → 插件更新失败(issue #43)。
|
|
55
|
+
* 包内路径上的 SQLite 连接一律不常驻,见 openIndexWriter。
|
|
56
|
+
* @param {string} dir 要判断的目录
|
|
57
|
+
* @param {string} [packageDir] 插件包根目录(默认按本模块位置推;测试可传)
|
|
58
|
+
*/
|
|
59
|
+
export function isInsidePluginPackage(dir, packageDir) {
|
|
60
|
+
try {
|
|
61
|
+
const target = resolve(dir)
|
|
62
|
+
const pkg = pluginPackageDir(packageDir)
|
|
63
|
+
return target === pkg || target.startsWith(pkg + sep)
|
|
64
|
+
} catch {
|
|
65
|
+
return false
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* 删除图库时该删哪个目录。只认两种路径,别的一律拒绝(防越界/防误删):
|
|
71
|
+
* - 内置包:插件包内 `memes/<id>`
|
|
72
|
+
* - 用户包:扫描目录子树里一个真正的包目录(`<packsDir>/<id>`,或历史遗留的嵌套包)
|
|
73
|
+
* @param {{id?: string, path?: string, source?: string}} pack listAllPacks() 的一项
|
|
74
|
+
* @param {string} packsDir 当前扫描目录
|
|
75
|
+
*/
|
|
76
|
+
export function packDeleteDir(pack, packsDir) {
|
|
77
|
+
const id = String((pack && pack.id) || '').trim()
|
|
78
|
+
if (!pack || !pack.path || !id) throw new Error('图库信息不完整')
|
|
79
|
+
const dir = resolve(pack.path)
|
|
80
|
+
if (pack.source === 'bundled') {
|
|
81
|
+
if (dir !== resolve(join(bundledPacksDir(), id))) throw new Error('图库目录与预期不符,已拒绝删除')
|
|
82
|
+
return dir
|
|
83
|
+
}
|
|
84
|
+
// 用户包:以前只认 `<packsDir>/<id>` 这一层,于是历史遗留的嵌套包(见 scanPacks)
|
|
85
|
+
// 能列在设置页里却删不掉。放宽成「packsDir 子树 + 目录名正好是包 id」,多层嵌套可删,
|
|
86
|
+
// 但仍然碰不到扫描目录本身,也删不到扫描目录外面的任何东西。
|
|
87
|
+
const root = resolve(String(packsDir || ''))
|
|
88
|
+
if (!root) throw new Error('图库目录无效,已拒绝删除')
|
|
89
|
+
if (dir === root) throw new Error('这个图库就是当前的「图库目录」本身,请先把它改到上级目录再删')
|
|
90
|
+
if (basename(dir) === id && dir.startsWith(root + sep)) return dir
|
|
91
|
+
throw new Error('图库目录与预期不符,已拒绝删除')
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* 模型可以用的图库 id 列表(设置页每张卡片上的开关)。
|
|
96
|
+
* 没设置过 `enabledPacks` 时只算当前图库——保持「装完即用」的旧行为,
|
|
97
|
+
* 用户一旦拨过开关就以显式列表为准(可以同时开多个)。
|
|
98
|
+
* 已删除/已卸载的 id 会被过滤掉。
|
|
99
|
+
*/
|
|
100
|
+
export function enabledPackIds(settings = {}, packs = [], activeId = '') {
|
|
101
|
+
const saved = Array.isArray(settings.enabledPacks) ? settings.enabledPacks.map(String) : null
|
|
102
|
+
if (saved === null) return activeId ? [activeId] : []
|
|
103
|
+
const alive = new Set(packs.map((p) => p.id))
|
|
104
|
+
return saved.filter((id) => alive.has(id))
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function isPackDir(dir) {
|
|
108
|
+
try {
|
|
109
|
+
return statSync(dir).isDirectory() && existsSync(join(dir, 'index.db'))
|
|
110
|
+
} catch {
|
|
111
|
+
return false
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** 读 manifest + 张数。id 以文件夹名为准(切换键稳定)。 */
|
|
116
|
+
export function readPackMeta(dir, id = basename(dir), source = 'custom') {
|
|
117
|
+
let name = id
|
|
118
|
+
let description = ''
|
|
119
|
+
let version = ''
|
|
120
|
+
try {
|
|
121
|
+
const m = JSON.parse(readFileSync(join(dir, 'manifest.json'), 'utf8'))
|
|
122
|
+
if (m && m.name) name = String(m.name)
|
|
123
|
+
if (m && m.description) description = String(m.description)
|
|
124
|
+
if (m && m.version) version = String(m.version)
|
|
125
|
+
} catch { /* 无 manifest 也能当包用 */ }
|
|
126
|
+
let count = 0
|
|
127
|
+
let cover = ''
|
|
128
|
+
try {
|
|
129
|
+
const db = new DatabaseSync(join(dir, 'index.db'), { readOnly: true })
|
|
130
|
+
count = Number(db.prepare('SELECT COUNT(*) AS n FROM memes').get().n) || 0
|
|
131
|
+
// 封面用图库自己的一张图(相对路径),装完的那份就在本地,不必再拉远程预览图。
|
|
132
|
+
// 取法固定:优先 happy 桶里字典序第一张,保证同一图库每次算出来同一张。
|
|
133
|
+
const row = db.prepare("SELECT path FROM memes ORDER BY (tag = 'happy') DESC, path ASC LIMIT 1").get()
|
|
134
|
+
if (row && row.path) cover = String(row.path)
|
|
135
|
+
db.close()
|
|
136
|
+
} catch { /* 空库或坏库 */ }
|
|
137
|
+
return { id, name, description, version, count, cover, path: resolve(dir), source }
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* 扫描可切换图库:插件内置 memes/* + 用户扫描目录下的一层子文件夹。
|
|
142
|
+
* 同 id 时用户目录覆盖内置(方便自己改官方包),同层里顶层优先。
|
|
143
|
+
*
|
|
144
|
+
* 历史遗留(issue #23):扫描目录被设成某个包目录自己时(设置页「选择目录」很容易点到包
|
|
145
|
+
* 文件夹),之后导入的包会嵌在那个包里面 → `memes/<主库>/<子库>/index.db`。这不是设计内的
|
|
146
|
+
* 布局,但已经躺在用户磁盘上了,所以这里额外容忍两种形状,免得图库「在磁盘上却扫不到」:
|
|
147
|
+
* 1. 扫描目录本身就是包 → 也当包收进来,否则它自己会从列表里消失(比嵌套更迷惑)
|
|
148
|
+
* 2. 包目录下再嵌一层包 → 一起收(顶层优先,同 id 不覆盖)
|
|
149
|
+
* 新导入不会再生成这种布局:setPacksDir 拒绝把包目录当扫描目录。
|
|
150
|
+
*/
|
|
151
|
+
export function scanPacks(packsDir = defaultPacksDir()) {
|
|
152
|
+
const byId = new Map()
|
|
153
|
+
const addPack = (dir, id, source) => {
|
|
154
|
+
if (!id || byId.has(id)) return
|
|
155
|
+
byId.set(id, readPackMeta(dir, id, source))
|
|
156
|
+
}
|
|
157
|
+
const addFrom = (parent, source) => {
|
|
158
|
+
if (!parent || !existsSync(parent)) return
|
|
159
|
+
if (isPackDir(parent)) addPack(parent, basename(parent), source)
|
|
160
|
+
let names
|
|
161
|
+
try { names = readdirSync(parent) } catch { return }
|
|
162
|
+
for (const name of names) {
|
|
163
|
+
const dir = join(parent, name)
|
|
164
|
+
if (!isPackDir(dir)) continue
|
|
165
|
+
addPack(dir, name, source)
|
|
166
|
+
let subs
|
|
167
|
+
try { subs = readdirSync(dir) } catch { continue }
|
|
168
|
+
for (const sub of subs) {
|
|
169
|
+
const subdir = join(dir, sub)
|
|
170
|
+
if (!isPackDir(subdir)) continue
|
|
171
|
+
addPack(subdir, sub, source)
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
addFrom(bundledPacksDir(), 'bundled')
|
|
176
|
+
addFrom(packsDir, 'user')
|
|
177
|
+
return [...byId.values()]
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** 设置 packId > memeRoot > patch config > 内置默认。 */
|
|
181
|
+
export function resolveActiveRoot(settings = {}, configRoot) {
|
|
182
|
+
const packs = scanPacks(settings.packsDir || defaultPacksDir())
|
|
183
|
+
const packId = String(settings.packId || '').trim()
|
|
184
|
+
if (packId && packId !== '_custom') {
|
|
185
|
+
const hit = packs.find((p) => p.id === packId)
|
|
186
|
+
if (hit) return hit.path
|
|
187
|
+
}
|
|
188
|
+
// 记住的 memeRoot 可能已经不存在了(比如内置包在升级后被移除/用户删掉了图库目录)。
|
|
189
|
+
// 这里只认真正有 index.db 的目录,否则一路回落到内置默认包——历史教训:把死路径
|
|
190
|
+
// 传给 MemesStore 会抛错,调用方 return,整个插件都装不起来。
|
|
191
|
+
if (settings.memeRoot && isPackDir(settings.memeRoot)) return settings.memeRoot
|
|
192
|
+
if (configRoot && isPackDir(configRoot)) return configRoot
|
|
193
|
+
return defaultMemeRoot()
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** 热切换时工具闭包仍指向同一对象:replace 内部 store。 */
|
|
197
|
+
export function liveStore(store) {
|
|
198
|
+
const box = {
|
|
199
|
+
get root() { return box._s.root },
|
|
200
|
+
list(...a) { return box._s.list(...a) },
|
|
201
|
+
search(...a) { return box._s.search(...a) },
|
|
202
|
+
sampleMood(...a) { return box._s.sampleMood(...a) },
|
|
203
|
+
resolveStored(...a) { return box._s.resolveStored(...a) },
|
|
204
|
+
/** 写库之后刷新内存索引快照(store 内部已关闭连接,不再有长期句柄,#43)。 */
|
|
205
|
+
refresh() { if (typeof box._s.refresh === 'function') box._s.refresh() },
|
|
206
|
+
replace(next) {
|
|
207
|
+
const prev = box._s
|
|
208
|
+
box._s = next
|
|
209
|
+
if (prev && prev !== next && typeof prev.close === 'function') prev.close()
|
|
210
|
+
},
|
|
211
|
+
}
|
|
212
|
+
box._s = store
|
|
213
|
+
return box
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** 模型只认这 6 个情绪桶;磁盘上仍是细 tag(路径不改)。 */
|
|
217
|
+
const MOODS = {
|
|
218
|
+
happy: ['happy', 'like', 'meow', 'givemoney', 'color'],
|
|
219
|
+
angry: ['angry', 'fool', 'baka'],
|
|
220
|
+
sad: ['sad', 'sigh'],
|
|
221
|
+
shy: ['shy'],
|
|
222
|
+
confused: ['confused', 'surprised', 'see'],
|
|
223
|
+
daily: ['daily', 'sleep', 'morning', 'work', 'cpu', 'reply'],
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
const MOOD_WORDS = {
|
|
227
|
+
happy: '开心 高兴 兴奋 喜欢 卖萌 可爱 比心 哈哈 欢迎 得意 好耶 满意',
|
|
228
|
+
angry: '生气 愤怒 暴躁 笨蛋 傻瓜 嫌弃 逮',
|
|
229
|
+
sad: '难过 哭 委屈 叹气 无语 求饶 怂 晕',
|
|
230
|
+
shy: '害羞 腼腆 脸红 花痴',
|
|
231
|
+
confused: '困惑 疑惑 惊讶 问号 懵 惊吓 震惊',
|
|
232
|
+
daily: '困 睡觉 早上好 打招呼 你好 上班 下班 摸鱼 工作 熬夜 吃饭 干饭 饿 日常',
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
export function moodNames() {
|
|
236
|
+
return Object.keys(MOODS)
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function fineTagsFor(tag) {
|
|
240
|
+
const t = String(tag || '').trim().toLowerCase()
|
|
241
|
+
if (!t) return null
|
|
242
|
+
if (MOODS[t]) return MOODS[t]
|
|
243
|
+
for (const fine of Object.values(MOODS)) {
|
|
244
|
+
if (fine.includes(t)) return [t]
|
|
245
|
+
}
|
|
246
|
+
return [t]
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
const MOOD_DICT =
|
|
250
|
+
'happy 开心(卖萌/可爱/喜欢) / angry 生气 / sad 难过(无语/求饶) / shy 害羞 / confused 困惑惊讶 / daily 日常(睡觉/上班/早上好)'
|
|
251
|
+
|
|
252
|
+
function moodsFromQuery(text) {
|
|
253
|
+
const hit = []
|
|
254
|
+
for (const [mood, words] of Object.entries(MOOD_WORDS)) {
|
|
255
|
+
if (words.split(/\s+/).some((w) => w && text.includes(w))) hit.push(mood)
|
|
256
|
+
}
|
|
257
|
+
return hit
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** tag 优先;否则用 query 里的口语词推断情绪。 */
|
|
261
|
+
export function resolveMood(tag, query) {
|
|
262
|
+
const t = String(tag || '').trim().toLowerCase()
|
|
263
|
+
if (t) {
|
|
264
|
+
if (MOODS[t]) return t
|
|
265
|
+
for (const [mood, fine] of Object.entries(MOODS)) {
|
|
266
|
+
if (fine.includes(t)) return mood
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
const q = String(query || '').trim().toLowerCase()
|
|
270
|
+
if (!q) return null
|
|
271
|
+
if (MOODS[q]) return q
|
|
272
|
+
return moodsFromQuery(q)[0] || null
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
function pickRandom(rows, n) {
|
|
276
|
+
const copy = rows.slice()
|
|
277
|
+
for (let i = copy.length - 1; i > 0; i--) {
|
|
278
|
+
const j = Math.floor(Math.random() * (i + 1))
|
|
279
|
+
const tmp = copy[i]
|
|
280
|
+
copy[i] = copy[j]
|
|
281
|
+
copy[j] = tmp
|
|
282
|
+
}
|
|
283
|
+
return copy.slice(0, n)
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** 关键词分词:空格/逗号/顿号/斜杠分隔,小写去重。中文词整词先搜,不预先切。 */
|
|
287
|
+
export function keywordTokens(query) {
|
|
288
|
+
const raw = String(query || '').trim().toLowerCase()
|
|
289
|
+
if (!raw) return []
|
|
290
|
+
return [...new Set(raw.split(/[\s,,、;;/|]+/).filter(Boolean))]
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** 整词全都没命中时的兜底拆词:「生气猫」→ 生气 / 气猫。 */
|
|
294
|
+
function biGrams(tokens) {
|
|
295
|
+
const out = []
|
|
296
|
+
for (const t of tokens) {
|
|
297
|
+
if (t.length < 3 || !/[\u4e00-\u9fff]/.test(t)) continue
|
|
298
|
+
for (let i = 0; i + 2 <= t.length; i++) out.push(t.slice(i, i + 2))
|
|
299
|
+
}
|
|
300
|
+
return [...new Set(out)]
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** keywords 的分词(与 keywordTokens 同分隔符,但保留原大小写:清洗后要原样写回) */
|
|
304
|
+
const keywordWords = (s) => String(s || '').split(/[\s,,、;;/|]+/).filter(Boolean)
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* 高频关键词清洗(issue #30 附带的建议)。
|
|
308
|
+
*
|
|
309
|
+
* 外部图库常把「角色大标签」写进每一条的 keywords:deepseek-chan 里 4 个词各出现在
|
|
310
|
+
* 1407/1407 条,搜「GPT」于是命中全库(official-001 的「表情包」占 70%、dafeiyu-001 的
|
|
311
|
+
* 「大肥鱼」占 100%,同类)。判定原则:出现在 ≥50% 条目里的词对检索零信息量 ——
|
|
312
|
+
* 比维护黑名单通用,导入时算一遍词频就行。
|
|
313
|
+
*
|
|
314
|
+
* 只在条目数 ≥ minRows 时动手:小图库里的重复词往往是真关键词
|
|
315
|
+
* (3 张猫图里的「猫」出现在 100% 条目里,但它是这张库唯一的检索入口)。
|
|
316
|
+
*
|
|
317
|
+
* @param {Array<{keywords?: string}>} rows 全部条目(只需要 keywords)
|
|
318
|
+
* @param {{threshold?: number, minRows?: number}} [opts]
|
|
319
|
+
* @returns {{total: number, drop: string[], cleaned: (string|null)[]}}
|
|
320
|
+
* drop: 被剔掉的词(小写);cleaned: 每条清洗后的 keywords,没变的条目是 null。
|
|
321
|
+
*/
|
|
322
|
+
export function pruneCommonKeywords(rows, { threshold = 0.5, minRows = 8 } = {}) {
|
|
323
|
+
const list = Array.isArray(rows) ? rows : []
|
|
324
|
+
const total = list.length
|
|
325
|
+
const none = list.map(() => null)
|
|
326
|
+
if (total < minRows) return { total, drop: [], cleaned: none }
|
|
327
|
+
const words = list.map((row) => keywordWords(row && row.keywords))
|
|
328
|
+
const counts = new Map()
|
|
329
|
+
for (const toks of words) {
|
|
330
|
+
for (const w of new Set(toks.map((t) => t.toLowerCase()))) counts.set(w, (counts.get(w) || 0) + 1)
|
|
331
|
+
}
|
|
332
|
+
// 至少有两条会命中才剔:不然「过半」在小样本里可能落到 1 条上
|
|
333
|
+
const floor = Math.max(2, Math.ceil(total * threshold))
|
|
334
|
+
const drop = [...counts].filter(([, n]) => n >= floor).map(([w]) => w)
|
|
335
|
+
if (drop.length === 0) return { total, drop: [], cleaned: none }
|
|
336
|
+
const dropSet = new Set(drop)
|
|
337
|
+
return {
|
|
338
|
+
total,
|
|
339
|
+
drop,
|
|
340
|
+
cleaned: words.map((toks) => {
|
|
341
|
+
const keep = toks.filter((w) => !dropSet.has(w.toLowerCase()))
|
|
342
|
+
return keep.length === toks.length ? null : keep.join(' ')
|
|
343
|
+
}),
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* 对已落盘的图库做一次高频关键词清洗(导入/安装流程调用)。
|
|
349
|
+
* 只改 keywords 字段,图片和其它字段都不动;这是检索质量的增强,失败不该拖垮安装,
|
|
350
|
+
* 所以调用方一律 try/catch。
|
|
351
|
+
* @returns {{drop: string[], changed: number}} 剔掉的词与改动的条目数
|
|
352
|
+
*/
|
|
353
|
+
export function prunePackKeywords(indexPath, opts) {
|
|
354
|
+
const db = new DatabaseSync(indexPath)
|
|
355
|
+
try {
|
|
356
|
+
const rows = db.prepare("SELECT rowid AS rid, COALESCE(keywords, '') AS keywords FROM memes").all()
|
|
357
|
+
const { drop, cleaned } = pruneCommonKeywords(rows, opts)
|
|
358
|
+
if (drop.length === 0) return { drop: [], changed: 0 }
|
|
359
|
+
let changed = 0
|
|
360
|
+
const update = db.prepare('UPDATE memes SET keywords = ? WHERE rowid = ?')
|
|
361
|
+
for (let i = 0; i < rows.length; i++) {
|
|
362
|
+
if (cleaned[i] === null) continue
|
|
363
|
+
update.run(cleaned[i], rows[i].rid)
|
|
364
|
+
changed++
|
|
365
|
+
}
|
|
366
|
+
return { drop, changed }
|
|
367
|
+
} finally {
|
|
368
|
+
db.close()
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
const rowHay = (row) => (
|
|
373
|
+
(row.tag || '') + ' ' + (row.caption || '') + ' ' + (row.keywords || '') + ' ' + (row.file_name || '')
|
|
374
|
+
).toLowerCase()
|
|
375
|
+
|
|
376
|
+
/**
|
|
377
|
+
* 关键词搜图(纯函数:面板/工具/跨图库合并共用)。
|
|
378
|
+
* 排序:全部关键词都命中的优先;没有全命中就取命中词数最多的那一档;
|
|
379
|
+
* 同一档内随机——同一个词反复 search 能换一批,不会每次都撞同一张。
|
|
380
|
+
* @returns {{query: string, tokens: string[], memes: object[]}}
|
|
381
|
+
*/
|
|
382
|
+
export function searchRows(rows, query, limit = 8) {
|
|
383
|
+
const tokens = keywordTokens(query)
|
|
384
|
+
if (tokens.length === 0) return { query: '', tokens: [], memes: [] }
|
|
385
|
+
const scan = (words) => {
|
|
386
|
+
const hits = []
|
|
387
|
+
for (const row of rows) {
|
|
388
|
+
const hay = rowHay(row)
|
|
389
|
+
let score = 0
|
|
390
|
+
for (const w of words) if (hay.includes(w)) score++
|
|
391
|
+
if (score > 0) hits.push({ row, score })
|
|
392
|
+
}
|
|
393
|
+
return hits
|
|
394
|
+
}
|
|
395
|
+
let hits = scan(tokens)
|
|
396
|
+
if (hits.length === 0) {
|
|
397
|
+
const grams = biGrams(tokens)
|
|
398
|
+
if (grams.length) hits = scan(grams)
|
|
399
|
+
}
|
|
400
|
+
if (hits.length === 0) return { query: tokens.join(' '), tokens, memes: [] }
|
|
401
|
+
const best = Math.max(...hits.map((h) => h.score))
|
|
402
|
+
return {
|
|
403
|
+
query: tokens.join(' '),
|
|
404
|
+
tokens,
|
|
405
|
+
memes: pickRandom(hits.filter((h) => h.score === best).map((h) => h.row), limit),
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/** 图库索引的读取语句(内存快照和一次性读取共用)。 */
|
|
410
|
+
const SELECT_ROWS = 'SELECT path, tag, file_name, caption, COALESCE(keywords, \'\') AS keywords FROM memes'
|
|
411
|
+
|
|
412
|
+
/**
|
|
413
|
+
* 图库索引(只读检索)。
|
|
414
|
+
*
|
|
415
|
+
* issue #43:以前这里在构造时打开 SQLite 连接并**一直持有**。插件默认激活内置图库
|
|
416
|
+
* (`<插件包>/memes/dafeiyu-001`),它就在 npm 包目录里;Windows 上只要目录里还有
|
|
417
|
+
* 打开的文件,`rename` 该目录就会 EPERM/EBUSY,而插件市场更新正是用 pnpm 把
|
|
418
|
+
* `node_modules/dsh-meme` 整个目录改名替换 → 更新失败(`ERR_PNPM_EPERM ... rename`)。
|
|
419
|
+
* 现在构造时一次性把索引读进内存并立刻关掉连接;写操作由 openIndexWriter 落盘后
|
|
420
|
+
* 调 refresh() 刷新快照。索引只有几千行(947K 的图库,索引本身几百 KB),
|
|
421
|
+
* 常驻内存的代价可以忽略,换来的好处是插件运行期**不占用图库文件**。
|
|
422
|
+
*/
|
|
423
|
+
export class MemesStore {
|
|
424
|
+
constructor(root = defaultMemeRoot()) {
|
|
425
|
+
this.root = resolve(root)
|
|
426
|
+
if (!existsSync(join(this.root, 'index.db'))) {
|
|
427
|
+
throw new Error('缺少表情包索引: ' + join(this.root, 'index.db'))
|
|
428
|
+
}
|
|
429
|
+
this.rows = this.readRows()
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/** 一次性读全表并关闭连接(不在磁盘上留长连接)。 */
|
|
433
|
+
readRows() {
|
|
434
|
+
const db = new DatabaseSync(join(this.root, 'index.db'), { readOnly: true })
|
|
435
|
+
try {
|
|
436
|
+
return db.prepare(SELECT_ROWS).all()
|
|
437
|
+
} finally {
|
|
438
|
+
try { db.close() } catch { /* 已关闭 */ }
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/** 写操作(openIndexWriter)落盘后刷新内存快照,否则校验/搜图还看到旧数据。 */
|
|
443
|
+
refresh() {
|
|
444
|
+
this.rows = this.readRows()
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/**
|
|
448
|
+
* 列表情包:tag 为情绪桶或细分类;query 只做 caption/keywords 子串(管理面板用)。
|
|
449
|
+
* exact = true 时按 tag 精确匹配、不做情绪桶展开——管理面板的分类下拉列的是
|
|
450
|
+
* 图库里真实的 tag,选「开心」却混进 like/meow 的桶展开行为会把用户搞糊涂(用户反馈)。
|
|
451
|
+
*/
|
|
452
|
+
list(tag, query, exact = false) {
|
|
453
|
+
const rows = this.rows
|
|
454
|
+
const tags = moodNames()
|
|
455
|
+
let memes = rows
|
|
456
|
+
if (exact && tag) {
|
|
457
|
+
memes = memes.filter((m) => m.tag === String(tag).trim().toLowerCase())
|
|
458
|
+
} else {
|
|
459
|
+
const fine = fineTagsFor(tag)
|
|
460
|
+
if (fine) memes = memes.filter((m) => fine.includes(m.tag))
|
|
461
|
+
}
|
|
462
|
+
const q = query && String(query).trim().toLowerCase()
|
|
463
|
+
if (q) {
|
|
464
|
+
const tokens = q.split(/\s+/).filter(Boolean)
|
|
465
|
+
memes = memes.filter((m) => {
|
|
466
|
+
const hay = (m.tag + ' ' + (m.caption ?? '') + ' ' + (m.keywords ?? '')).toLowerCase()
|
|
467
|
+
return tokens.some((t) => hay.includes(t))
|
|
468
|
+
})
|
|
469
|
+
}
|
|
470
|
+
return { memes, tags }
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/**
|
|
474
|
+
* 关键词搜图。给了 tag 就先把范围限在那个情绪桶里(细 tag 展开同 list),
|
|
475
|
+
* 于是「情绪 + 关键词」= 在桶里筛词。
|
|
476
|
+
* @returns {{query: string, tokens: string[], memes: object[], tags: string[]}}
|
|
477
|
+
*/
|
|
478
|
+
search(query, n = 8, tag = null) {
|
|
479
|
+
const rows = this.rows
|
|
480
|
+
const fine = fineTagsFor(tag)
|
|
481
|
+
const scoped = fine ? rows.filter((m) => fine.includes(m.tag)) : rows
|
|
482
|
+
return { ...searchRows(scoped, query, n), tags: moodNames() }
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/** 按情绪取池,随机抽 n 张给模型看 caption。 */
|
|
486
|
+
sampleMood(tag, query, n = 5) {
|
|
487
|
+
const mood = resolveMood(tag, query)
|
|
488
|
+
if (!mood) return { mood: null, memes: [], tags: moodNames() }
|
|
489
|
+
const { memes } = this.list(mood)
|
|
490
|
+
return { mood, memes: pickRandom(memes, n), tags: moodNames() }
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/** 把索引内相对路径解析为绝对路径(不允许逃出图库根)。 */
|
|
494
|
+
resolveStored(stored) {
|
|
495
|
+
const target = resolve(this.root, stored)
|
|
496
|
+
if (target !== this.root && !target.startsWith(this.root + sep)) {
|
|
497
|
+
throw new Error('路径超出表情包目录')
|
|
498
|
+
}
|
|
499
|
+
if (!existsSync(target)) {
|
|
500
|
+
throw new Error('文件不存在: ' + stored)
|
|
501
|
+
}
|
|
502
|
+
return target
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
/** 接口保留:连接已在构造时关闭,热切换时调用 close() 不需要额外动作。 */
|
|
506
|
+
close() {}
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
/**
|
|
510
|
+
* 图库索引的**可写**连接(管理 API 上传/删除、learn_meme 学图用)。
|
|
511
|
+
*
|
|
512
|
+
* 用户图库(~/.dsh/meme-packs)保持常驻连接,和以前一样省去每次开关库的开销。
|
|
513
|
+
* 插件包内的图库则绝不常驻:更新时 pnpm 要 rename 整个包目录,Windows 上目录里
|
|
514
|
+
* 只要有打开的文件就会 EPERM(#43)。这类目录改成每条语句临时 open→执行→close,
|
|
515
|
+
* 写完立刻释放;对调用方暴露的 prepare/exec/close 接口保持不变。
|
|
516
|
+
*
|
|
517
|
+
* @param {string} root 图库根目录
|
|
518
|
+
* @param {{packageDir?: string}} [opts] packageDir 供测试指定「插件包根」,默认按本模块位置推
|
|
519
|
+
*/
|
|
520
|
+
export function openIndexWriter(root, opts = {}) {
|
|
521
|
+
const dir = resolve(root)
|
|
522
|
+
const indexPath = join(dir, 'index.db')
|
|
523
|
+
// 用户图库(包外):维持常驻可写连接。
|
|
524
|
+
if (!isInsidePluginPackage(dir, opts.packageDir)) {
|
|
525
|
+
const db = new DatabaseSync(indexPath)
|
|
526
|
+
return {
|
|
527
|
+
prepare: (...args) => db.prepare(...args),
|
|
528
|
+
exec: (...args) => db.exec(...args),
|
|
529
|
+
close: () => { try { db.close() } catch { /* 已关闭 */ } },
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
// 插件包内:每条语句开、关一次,插件运行期不占包内文件。
|
|
533
|
+
const withDb = (fn) => {
|
|
534
|
+
const db = new DatabaseSync(indexPath)
|
|
535
|
+
try {
|
|
536
|
+
return fn(db)
|
|
537
|
+
} finally {
|
|
538
|
+
try { db.close() } catch { /* 已关闭 */ }
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
const statement = (sql) => ({
|
|
542
|
+
run: (...args) => withDb((db) => db.prepare(sql).run(...args)),
|
|
543
|
+
get: (...args) => withDb((db) => db.prepare(sql).get(...args)),
|
|
544
|
+
all: (...args) => withDb((db) => db.prepare(sql).all(...args)),
|
|
545
|
+
})
|
|
546
|
+
return {
|
|
547
|
+
prepare: statement,
|
|
548
|
+
exec: (sql) => withDb((db) => db.exec(sql)),
|
|
549
|
+
close: () => { /* 无常驻连接 */ },
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
/**
|
|
554
|
+
* 已知 IM 渠道的 id(rpcId 前缀)。与 @xmanrui/dsh-im 的 channel 列表保持一致:
|
|
555
|
+
* 它给每条进来的消息写 `source.rpcId = <channel>-<uuid>`(steer 消息是
|
|
556
|
+
* `<channel>-steer-<uuid>`),旧版还会把 `<channel>-` 直接拼进会话 id。
|
|
557
|
+
* dsh-im 将来加渠道时在这里补一项即可,没列到的渠道会退回 Web 的标记模式。
|
|
558
|
+
*/
|
|
559
|
+
export const IM_CHANNEL_PREFIXES = Object.freeze([
|
|
560
|
+
'weixin', 'feishu', 'dingtalk', 'wecom', 'wecomapp', 'qq', 'slack', 'telegram',
|
|
561
|
+
'discord', 'whatsapp', 'imessage', 'matrix', 'email', 'office',
|
|
562
|
+
])
|
|
563
|
+
|
|
564
|
+
/** IM 渠道 id → 展示名(写进提示词/工具结果,让模型知道当前是哪个聊天软件)。 */
|
|
565
|
+
export const IM_CHANNEL_LABELS = Object.freeze({
|
|
566
|
+
weixin: '微信',
|
|
567
|
+
feishu: '飞书',
|
|
568
|
+
dingtalk: '钉钉',
|
|
569
|
+
wecom: '企业微信',
|
|
570
|
+
wecomapp: '企业微信应用',
|
|
571
|
+
qq: 'QQ',
|
|
572
|
+
slack: 'Slack',
|
|
573
|
+
telegram: 'Telegram',
|
|
574
|
+
discord: 'Discord',
|
|
575
|
+
whatsapp: 'WhatsApp',
|
|
576
|
+
imessage: 'iMessage',
|
|
577
|
+
matrix: 'Matrix',
|
|
578
|
+
email: '邮件',
|
|
579
|
+
office: 'AI Office',
|
|
580
|
+
})
|
|
581
|
+
|
|
582
|
+
const IM_UUID_PATTERN = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'
|
|
583
|
+
const IM_RPC_ID_RE = new RegExp('^(' + IM_CHANNEL_PREFIXES.join('|') + ')-(?:steer-)?' + IM_UUID_PATTERN + '$', 'u')
|
|
584
|
+
const IM_LEGACY_SESSION_ID_RE = new RegExp('^(' + IM_CHANNEL_PREFIXES.join('|') + ')-.+', 'u')
|
|
585
|
+
|
|
586
|
+
function sessionEventsOf(session) {
|
|
587
|
+
const events = typeof session?.snapshotEvents === 'function'
|
|
588
|
+
? session.snapshotEvents()
|
|
589
|
+
: session?.events
|
|
590
|
+
return Array.isArray(events) ? events : []
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
/**
|
|
594
|
+
* 这个会话当前这一轮是不是从 IM(dsh-im 的 QQ/微信/飞书…)进来的,是则返回渠道 id。
|
|
595
|
+
*
|
|
596
|
+
* 判据取「最后一条真实用户消息」的 rpcId 前缀,而不是扫全会话:同一个会话
|
|
597
|
+
* 可以在 Web 里创建、后来被 dsh-im 用 `/session` 绑到某个 IM 聊天(会话同步),
|
|
598
|
+
* 那样早先的 Web 消息和后来的 IM 消息会混在同一段日志里——机器人在哪个渠道
|
|
599
|
+
* 回复,取决于这一轮是从哪进来的。Web UI 的 rpcId 是没有渠道前缀的裸 uuid,
|
|
600
|
+
* 于是自然不命中。
|
|
601
|
+
*
|
|
602
|
+
* fork 出来的会话不能继承父会话的渠道(父子消息会混在事件流里),宿主两版
|
|
603
|
+
* Session 都暴露 inheritedEventCount,拿不到就不猜。
|
|
604
|
+
*/
|
|
605
|
+
export function imChannelOfSession(session) {
|
|
606
|
+
if (!session || typeof session !== 'object') return null
|
|
607
|
+
try {
|
|
608
|
+
const header = session.header && typeof session.header === 'object' ? session.header : null
|
|
609
|
+
const inherited = session.inheritedEventCount
|
|
610
|
+
if (header?.parentSession && !Number.isSafeInteger(inherited)) return null
|
|
611
|
+
const events = sessionEventsOf(session)
|
|
612
|
+
for (let i = events.length - 1; i >= 0; i--) {
|
|
613
|
+
const event = events[i]
|
|
614
|
+
if (!event || event.type !== 'user/message') continue
|
|
615
|
+
if (Number.isSafeInteger(inherited) && Number.isSafeInteger(event.seq) && event.seq < inherited) continue
|
|
616
|
+
const source = event.data && event.data.source
|
|
617
|
+
if (!source || source.kind !== 'user') continue
|
|
618
|
+
const rpcId = String(source.rpcId || '')
|
|
619
|
+
if (!rpcId) continue
|
|
620
|
+
const hit = IM_RPC_ID_RE.exec(rpcId)
|
|
621
|
+
if (hit) return hit[1]
|
|
622
|
+
// 最近一条用户消息有 rpcId、但没命中 IM 前缀:这一轮来自 Web/其他来源
|
|
623
|
+
return null
|
|
624
|
+
}
|
|
625
|
+
if (header?.parentSession) return null
|
|
626
|
+
// 旧版 dsh-im 把渠道写进会话 id;新版 id 是纯 uuid,只能靠上面的 rpcId
|
|
627
|
+
const id = typeof session.id === 'string'
|
|
628
|
+
? session.id
|
|
629
|
+
: typeof session.sessionId === 'string' ? session.sessionId : ''
|
|
630
|
+
const legacy = IM_LEGACY_SESSION_ID_RE.exec(id)
|
|
631
|
+
return legacy ? legacy[1] : null
|
|
632
|
+
} catch {
|
|
633
|
+
// 宿主会话对象处于半初始化/已释放状态时不能连累系统提示装配
|
|
634
|
+
return null
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
/**
|
|
639
|
+
* AI 的发送方式(设置页「发送方式」下拉框):
|
|
640
|
+
* - auto(默认):按渠道自动——Web 写 [表情: 描述] 由前端配图,IM 会话改走 dsh_im_return_file;
|
|
641
|
+
* - text:纯文字,不发表情图片(仍可查候选,但只用文字描述/接梗);
|
|
642
|
+
* - image:总是发图——Web 写标记,IM 必须调 dsh_im_return_file。
|
|
643
|
+
* 只影响 AI 怎么发,不改前端把 [表情: 描述] 配成图的渲染逻辑。
|
|
644
|
+
*/
|
|
645
|
+
export const SEND_MODES = ['auto', 'text', 'image']
|
|
646
|
+
export function normalizeSendMode(value) {
|
|
647
|
+
return SEND_MODES.includes(value) ? value : 'auto'
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
/**
|
|
651
|
+
* 表情排布方式(设置页「表情排布」下拉框,issue #50):
|
|
652
|
+
* - inline(默认):图与正文并排——图提到消息行行首,正文在右,短消息紧凑;
|
|
653
|
+
* - stacked:图独占一行在上,正文按正常宽度铺开在下,阅读宽度完整。
|
|
654
|
+
* 只影响前端把 [表情: 描述] 渲染成图后的排布,默认保持并排不改已有用户观感。
|
|
655
|
+
*/
|
|
656
|
+
export const LAYOUT_MODES = ['inline', 'stacked']
|
|
657
|
+
export function normalizeLayoutMode(value) {
|
|
658
|
+
return LAYOUT_MODES.includes(value) ? value : 'inline'
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
// ---- 用户收藏的稳定落点与图库目录扫描 ----
|
|
662
|
+
|
|
663
|
+
/** 扫描/收录认可的图片扩展(与上传、AI 学图一致) */
|
|
664
|
+
export const SCAN_IMAGE_EXTS = ['.jpg', '.jpeg', '.png', '.gif', '.webp']
|
|
665
|
+
|
|
666
|
+
const SCAN_TAG_RE = /^[a-z0-9_-]+$/
|
|
667
|
+
|
|
668
|
+
/**
|
|
669
|
+
* 手动放进图库目录的图片 → 索引行(扫描入库用,纯函数便于单测)。
|
|
670
|
+
* 分类取路径首段目录名(memes/<tag>/x.jpg → <tag>,<tag>/x.jpg → <tag>);
|
|
671
|
+
* 首段不是合法 tag、或图片散在根目录 → misc。path 保持磁盘上的真实相对路径
|
|
672
|
+
* (图片路由按索引 path 找文件,不能为了格式好看改写)。描述兜底用文件名去扩展名。
|
|
673
|
+
*/
|
|
674
|
+
export function scanRowFor(rel) {
|
|
675
|
+
const posix = String(rel || '').replace(/\\/g, '/').replace(/^\/+/, '')
|
|
676
|
+
const body = posix.startsWith('memes/') ? posix.slice('memes/'.length) : posix
|
|
677
|
+
const segs = body.split('/').filter(Boolean)
|
|
678
|
+
const file = segs[segs.length - 1] || ''
|
|
679
|
+
const tag = segs.length >= 2 && SCAN_TAG_RE.test(segs[0]) ? segs[0] : 'misc'
|
|
680
|
+
const dot = file.lastIndexOf('.')
|
|
681
|
+
const stem = dot > 0 ? file.slice(0, dot) : file
|
|
682
|
+
return { path: posix, tag, file_name: file, caption: stem.slice(0, 200) }
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
/**
|
|
686
|
+
* 递归列出图库目录下的图片文件(相对 root 的 posix 路径),跳过 index.db、
|
|
687
|
+
* manifest.json 与隐藏目录。用户「自己塞进文件夹」的图从这里入库:原始字节
|
|
688
|
+
* 原样保留——聊天附件通道会把 GIF 压成单帧,磁盘文件不会。
|
|
689
|
+
*/
|
|
690
|
+
export function walkPackImages(root) {
|
|
691
|
+
const out = []
|
|
692
|
+
const walk = (dir, prefix) => {
|
|
693
|
+
let entries = []
|
|
694
|
+
try { entries = readdirSync(dir, { withFileTypes: true }) } catch { return }
|
|
695
|
+
for (const e of entries) {
|
|
696
|
+
if (e.name.startsWith('.') || e.name === 'manifest.json' || e.name.startsWith('index.db')) continue
|
|
697
|
+
const abs = join(dir, e.name)
|
|
698
|
+
const rel = prefix ? prefix + '/' + e.name : e.name
|
|
699
|
+
if (e.isDirectory()) { walk(abs, rel); continue }
|
|
700
|
+
if (!e.isFile()) continue
|
|
701
|
+
const dot = e.name.lastIndexOf('.')
|
|
702
|
+
const ext = dot >= 0 ? e.name.slice(dot).toLowerCase() : ''
|
|
703
|
+
if (SCAN_IMAGE_EXTS.includes(ext)) out.push(rel)
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
walk(resolve(root), '')
|
|
707
|
+
return out.sort()
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
/**
|
|
711
|
+
* 确保一个最小图库存在于 dir(manifest.json + 空 index.db),已存在则不动。
|
|
712
|
+
* 给「我的收藏」这类程序化创建的稳定图库用。
|
|
713
|
+
*/
|
|
714
|
+
export function ensurePackAt(dir, meta) {
|
|
715
|
+
mkdirSync(dir, { recursive: true })
|
|
716
|
+
const indexPath = join(dir, 'index.db')
|
|
717
|
+
if (!existsSync(indexPath)) {
|
|
718
|
+
const db = new DatabaseSync(indexPath)
|
|
719
|
+
db.exec('CREATE TABLE IF NOT EXISTS memes (path TEXT PRIMARY KEY, tag TEXT, file_name TEXT, caption TEXT, keywords TEXT, mtime REAL, captioned_at REAL)')
|
|
720
|
+
db.close()
|
|
721
|
+
}
|
|
722
|
+
const manifestPath = join(dir, 'manifest.json')
|
|
723
|
+
if (!existsSync(manifestPath)) {
|
|
724
|
+
writeFileSync(manifestPath, JSON.stringify({ id: meta.id, name: meta.name, description: String(meta.description || ''), version: '1.0.0' }, null, 2))
|
|
725
|
+
}
|
|
726
|
+
return dir
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
/**
|
|
730
|
+
* 把 src 图库里的指定条目(索引行 + 文件)搬到 dst 图库的 memes/<tag>/ 下,保持分类。
|
|
731
|
+
* 用于把内置图库里用户后加的收藏搬去包外的稳定图库——插件升级会整个替换包目录,
|
|
732
|
+
* 留在里面的用户文件会被清掉。目标撞名时加时间缀;rename 跨盘失败回落 copy+unlink。
|
|
733
|
+
* 返回 { moved: [{from,to}], missing: [...] }(missing = 索引行或文件已不存在)。
|
|
734
|
+
*/
|
|
735
|
+
export function movePackEntries(srcRoot, dstRoot, paths) {
|
|
736
|
+
const moved = []
|
|
737
|
+
const missing = []
|
|
738
|
+
const src = openIndexWriter(srcRoot)
|
|
739
|
+
const dst = openIndexWriter(dstRoot)
|
|
740
|
+
try {
|
|
741
|
+
for (const rel of paths || []) {
|
|
742
|
+
const row = src.prepare('SELECT tag, file_name, caption, keywords FROM memes WHERE path = ?').get(String(rel))
|
|
743
|
+
const from = join(resolve(srcRoot), String(rel))
|
|
744
|
+
if (!row || !existsSync(from)) { missing.push(String(rel)); continue }
|
|
745
|
+
const tag = SCAN_TAG_RE.test(String(row.tag || '')) ? row.tag : 'misc'
|
|
746
|
+
let name = basename(String(rel))
|
|
747
|
+
let toRel = 'memes/' + tag + '/' + name
|
|
748
|
+
if (existsSync(join(resolve(dstRoot), toRel))) {
|
|
749
|
+
const dot = name.lastIndexOf('.')
|
|
750
|
+
name = (dot > 0 ? name.slice(0, dot) : name) + '_' + Date.now() + (dot > 0 ? name.slice(dot) : '')
|
|
751
|
+
toRel = 'memes/' + tag + '/' + name
|
|
752
|
+
}
|
|
753
|
+
const to = join(resolve(dstRoot), toRel)
|
|
754
|
+
mkdirSync(dirname(to), { recursive: true })
|
|
755
|
+
try { renameSync(from, to) } catch {
|
|
756
|
+
copyFileSync(from, to)
|
|
757
|
+
unlinkSync(from)
|
|
758
|
+
}
|
|
759
|
+
dst.prepare('INSERT OR REPLACE INTO memes (path, tag, file_name, caption, keywords, mtime, captioned_at) VALUES (?, ?, ?, ?, ?, ?, ?)')
|
|
760
|
+
.run(toRel, tag, name, row.caption || '', row.keywords || '', Date.now(), Date.now())
|
|
761
|
+
src.prepare('DELETE FROM memes WHERE path = ?').run(String(rel))
|
|
762
|
+
moved.push({ from: String(rel), to: toRel })
|
|
763
|
+
}
|
|
764
|
+
} finally {
|
|
765
|
+
try { src.close() } catch { /* 已关闭 */ }
|
|
766
|
+
try { dst.close() } catch { /* 已关闭 */ }
|
|
767
|
+
}
|
|
768
|
+
return { moved, missing }
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
/**
|
|
772
|
+
* 注册 send_meme 工具。
|
|
773
|
+
*
|
|
774
|
+
* 三种模式:
|
|
775
|
+
* - Web 模式(无 QQ 通道,有 urlPrefix):只保留 search——随机抽候选,
|
|
776
|
+
* 模型挑一张把 [表情: 描述] 写进回复,前端按描述配图,
|
|
777
|
+
* 不需要冗余的 send 动作;
|
|
778
|
+
* - IM 模式(Web 模式 + 本轮来自 dsh-im 的 QQ/微信等渠道):候选额外带绝对路径,
|
|
779
|
+
* IM 聊天不渲染 [表情: 描述] 标记,模型要把挑中的 path 交给 dsh-im 的
|
|
780
|
+
* `dsh_im_return_file` 作为原生图片发出;
|
|
781
|
+
* - QQ 模式(companionQq 可用):两步式,action=send 才是真正的投递动作。
|
|
782
|
+
*
|
|
783
|
+
* @param {object} ctx 插件上下文
|
|
784
|
+
* @param {MemesStore} memes 图库
|
|
785
|
+
* @param {(path: string, caption?: string) => void | null} sendImage QQ 通道发送
|
|
786
|
+
* (dsh-companion 的 companionQq.sendImage);传 null 时走 web 模式。
|
|
787
|
+
* @param {string | null} urlPrefix webServer 图片路由前缀(如 '/dsh-memes'),无则 null
|
|
788
|
+
* @param {object} [options]
|
|
789
|
+
* @param {(session: object) => string | null} [options.imChannelOf]
|
|
790
|
+
* 判断某个会话本轮来自哪个 IM 渠道(dsh-im 可用时由 index.js 传入;返回 null = 非 IM 或能力缺失)
|
|
791
|
+
* @param {boolean} [options.imReady] 注册时 dsh-im 是否已在进程内(只影响工具描述措辞)
|
|
792
|
+
* @param {() => string} [options.sendMode] 运行时读发送方式设置(auto/text/image)
|
|
793
|
+
* @param {() => Array<{tag: string, count: number}> | null} [options.tagStats]
|
|
794
|
+
* 跨启用图库的分类统计(按张数降序)。搜索没命中时用它给模型真实的换词建议,
|
|
795
|
+
* 而不是只甩一串静态情绪字典(issue #53)。
|
|
796
|
+
*/
|
|
797
|
+
function clampLimit(n) {
|
|
798
|
+
const x = typeof n === 'number' ? n : Number(n)
|
|
799
|
+
if (!Number.isFinite(x)) return 8
|
|
800
|
+
return Math.max(1, Math.min(20, Math.floor(x)))
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
export function registerSendMemeTool(ctx, memes, sendImage, urlPrefix = null, options = {}) {
|
|
804
|
+
const webMode = !sendImage && !!urlPrefix
|
|
805
|
+
const imChannelOf = typeof options.imChannelOf === 'function' ? options.imChannelOf : null
|
|
806
|
+
/** 注册时 dsh-im 是否已在进程内——只决定工具描述要不要提 IM 的发送方式 */
|
|
807
|
+
const imReady = options.imReady === true
|
|
808
|
+
/** 运行时的发送方式设置(auto/text/image):每次执行读一次,设置改了下一条消息就生效 */
|
|
809
|
+
const sendModeOf = typeof options.sendMode === 'function' ? options.sendMode : () => 'auto'
|
|
810
|
+
/** 跨启用图库的分类统计(张数降序);没有就退回静态情绪字典 */
|
|
811
|
+
const tagStatsOf = typeof options.tagStats === 'function' ? options.tagStats : () => null
|
|
812
|
+
/** 没命中时给模型的换词建议:真实分类统计优先,拉不到才用静态情绪字典(issue #53) */
|
|
813
|
+
const tagHint = () => {
|
|
814
|
+
try {
|
|
815
|
+
const stats = tagStatsOf()
|
|
816
|
+
if (Array.isArray(stats) && stats.length > 0) {
|
|
817
|
+
const top = stats.slice(0, 15).map((s) => s.tag + '(' + s.count + ')').join(' / ')
|
|
818
|
+
return '当前启用图库里的分类(按张数): ' + top
|
|
819
|
+
}
|
|
820
|
+
} catch { /* 统计失败退回字典 */ }
|
|
821
|
+
return '情绪字典: ' + MOOD_DICT
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
const parameters = {
|
|
825
|
+
tag: {
|
|
826
|
+
type: 'string',
|
|
827
|
+
description: '情绪范围(可选): ' + MOOD_DICT + '。只给 tag = 在该情绪里随机抽;tag + query = 在该情绪里按关键词筛。',
|
|
828
|
+
},
|
|
829
|
+
query: {
|
|
830
|
+
type: 'string',
|
|
831
|
+
description: '关键词(可选,想找特定的图就用它): 按 caption/关键词/图名子串搜,比只抽情绪准。中文词,空格分隔多个(如「猫」「生气 猫」「无语」);整词没命中会自动拆词重试。没给 tag 时,搜不到也会拿它推断情绪。',
|
|
832
|
+
},
|
|
833
|
+
limit: {
|
|
834
|
+
type: 'number',
|
|
835
|
+
description: '本次返回几张候选(1-20,默认 8)。拿不准就多抽点;不满意再 search 换一批。',
|
|
836
|
+
},
|
|
837
|
+
}
|
|
838
|
+
if (!webMode) {
|
|
839
|
+
parameters.action = {
|
|
840
|
+
type: 'string',
|
|
841
|
+
enum: ['search', 'send'],
|
|
842
|
+
description: 'search: 按情绪或关键词取候选; send: 发送挑中的 path',
|
|
843
|
+
}
|
|
844
|
+
parameters.path = { type: 'string', description: 'send 时要发的图路径(来自 search 候选列表)' }
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
ctx.tools.register(defineTool({
|
|
848
|
+
name: 'send_meme',
|
|
849
|
+
description: '发一张表情包。两种搜法:①只给 tag(情绪)→ 从该情绪里随机抽;②给 query(关键词)→ 在 caption/关键词/图名里搜,想找特定的图(「猫」「比心」「摸鱼」)就用这个;两个都给 = 在该情绪里按关键词筛,最准。' +
|
|
850
|
+
'流程:给 tag/query → 系统返回若干张候选(带 caption,数量用 limit 自己定) → 看描述觉得贴就发;不满意再 search 换一批,还不行就换词/换情绪或回文字。' +
|
|
851
|
+
'情绪字典: ' + MOOD_DICT + '。' +
|
|
852
|
+
(webMode
|
|
853
|
+
? (imReady
|
|
854
|
+
? '发送方式看工具结果末尾的说明:Web 聊天把 [表情: 描述] 原样写进回复(描述抄候选原文,不要带网址);IM(QQ/微信等)聊天调用 dsh_im_return_file 传候选的 path 发原生图片,不要写 [表情: ...] 标记。'
|
|
855
|
+
: '挑中后把 [表情: 描述] 原样写进回复(描述必须抄候选原文,不要带网址)——自己编的描述前端配不上图。')
|
|
856
|
+
: '两步:search 看候选,再用 send + path 发出。') +
|
|
857
|
+
'发送方式以设置里的「发送方式」下拉框为准(自动/纯文字/图片),每次结果末尾的「发图」说明会告诉你怎么发。' +
|
|
858
|
+
'气氛对了就主动发;发完短接,让图自己说话。',
|
|
859
|
+
parameters,
|
|
860
|
+
output: {
|
|
861
|
+
schema: { type: 'json' },
|
|
862
|
+
render: (_args, value) => [{ type: 'text', text: value.message }],
|
|
863
|
+
},
|
|
864
|
+
execute(args, exec) {
|
|
865
|
+
const action = webMode ? 'search' : (args.action === 'send' ? 'send' : 'search')
|
|
866
|
+
const query = typeof args.query === 'string' ? args.query.trim() : ''
|
|
867
|
+
const tag = typeof args.tag === 'string' ? args.tag.trim().toLowerCase() : ''
|
|
868
|
+
const path = typeof args.path === 'string' ? args.path.trim() : ''
|
|
869
|
+
const limit = clampLimit(args.limit)
|
|
870
|
+
const sendMode = normalizeSendMode(sendModeOf())
|
|
871
|
+
const textMode = sendMode === 'text'
|
|
872
|
+
const imageMode = sendMode === 'image'
|
|
873
|
+
|
|
874
|
+
if (action === 'send') {
|
|
875
|
+
if (textMode) {
|
|
876
|
+
return { ok: false, message: '当前发送方式是「纯文字」,不发图片;直接用文字接梗/描述即可' }
|
|
877
|
+
}
|
|
878
|
+
if (!path) {
|
|
879
|
+
return { ok: false, message: 'send 需要 path——先 search 看候选,再挑一张发' }
|
|
880
|
+
}
|
|
881
|
+
let absolute
|
|
882
|
+
try {
|
|
883
|
+
absolute = memes.resolveStored(path)
|
|
884
|
+
} catch (error) {
|
|
885
|
+
return { ok: false, message: '未知路径: ' + path + ' —— 用 search 的候选 path' }
|
|
886
|
+
}
|
|
887
|
+
if (sendImage) {
|
|
888
|
+
// companionQq.sendImage 是 async:失败得到的是 rejected Promise,同步 try/catch 抓不到。
|
|
889
|
+
// 漏出去会被宿主的 unhandledRejection 判成 "fatal load failure",直接把 DSH 进程退出。
|
|
890
|
+
const sendFailed = (error) => ({ ok: false, message: '发送失败: ' + (error instanceof Error ? error.message : String(error)) })
|
|
891
|
+
const sentOk = () => ({ ok: true, message: '已发送表情包', path })
|
|
892
|
+
try {
|
|
893
|
+
const sending = sendImage(absolute)
|
|
894
|
+
if (sending && typeof sending.then === 'function') return Promise.resolve(sending).then(sentOk, sendFailed)
|
|
895
|
+
return sentOk()
|
|
896
|
+
} catch (error) {
|
|
897
|
+
return sendFailed(error)
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
return { ok: false, message: '没有可用发送通道: ' + absolute }
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
// 这一轮来自 dsh-im 的 IM 渠道时,图片只能作为原生图片发出:
|
|
904
|
+
// [表情: 描述] 标记只有 Web 前端会配图,IM 聊天里它只是一行方括号文字。
|
|
905
|
+
// 所以候选要带上绝对路径,交给 dsh-im 的 dsh_im_return_file 投递。
|
|
906
|
+
const imChannel = !sendImage && imChannelOf ? imChannelOf(exec?.agent?.session) : null
|
|
907
|
+
// 纯文字模式:Web/IM 都不发图;候选不带路径,免得模型顺手把 path 交给投递工具
|
|
908
|
+
const imMode = !textMode && !sendImage && !!imChannel
|
|
909
|
+
const imLabel = imMode ? (IM_CHANNEL_LABELS[imChannel] || 'IM') : ''
|
|
910
|
+
|
|
911
|
+
const captionOf = (m) => String(m.caption || m.file_name || '').slice(0, 80)
|
|
912
|
+
/** 候选的绝对路径:IM 投递工具要的是磁盘路径,不能是图库内的相对路径/包前缀路径 */
|
|
913
|
+
const absolutePathOf = (m) => {
|
|
914
|
+
try {
|
|
915
|
+
return memes.resolveStored(m.path)
|
|
916
|
+
} catch {
|
|
917
|
+
return String(m.path || '')
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
/** 候选所属图库:跨库合并时 sampler 会给每行标 packName/packId(issue #53) */
|
|
921
|
+
const libraryOf = (m) => String(m.packName || m.packId || '')
|
|
922
|
+
|
|
923
|
+
const lines = (rows) => rows.map((m, i) => {
|
|
924
|
+
const caption = captionOf(m)
|
|
925
|
+
// 纯文字模式:只给描述,不给 [表情: …] 标记也不给路径——标记在前端仍会配成图
|
|
926
|
+
if (textMode) return (i + 1) + '. 描述=' + caption + ' | 分类=' + m.tag
|
|
927
|
+
// IM 模式不要用 "[tag] caption" 的方括号样式:模型会照着把方括号抄进回复,
|
|
928
|
+
// 而 IM 客户端只把方括号里的文字显示出来(用户看到的是 [无语死鱼脸] 之类)。
|
|
929
|
+
if (imMode) return (i + 1) + '. path=' + absolutePathOf(m) + ' | 分类=' + m.tag + ' | 描述=' + caption
|
|
930
|
+
return webMode
|
|
931
|
+
? (i + 1) + '. [表情: ' + caption + ']'
|
|
932
|
+
: (i + 1) + '. path=' + m.path + ' | [' + m.tag + '] ' + caption
|
|
933
|
+
})
|
|
934
|
+
const hits = (rows) => {
|
|
935
|
+
// 出处元信息(issue #53):path/library 进模型可见的 JSON(用户问「这图哪来的」
|
|
936
|
+
// 模型答得上),不进用户可见的行文本——Web 模式行里仍只有 [表情: 描述],
|
|
937
|
+
// 模型不会顺手把路径抄进回复。纯文字模式维持只给描述(路径会诱导投递工具)。
|
|
938
|
+
if (textMode) return rows.map((m) => ({ tag: m.tag, caption: captionOf(m), library: libraryOf(m) }))
|
|
939
|
+
if (imMode) return rows.map((m) => ({ path: absolutePathOf(m), tag: m.tag, caption: captionOf(m), library: libraryOf(m) }))
|
|
940
|
+
return webMode
|
|
941
|
+
? rows.map((m) => ({ caption: captionOf(m), path: m.path, library: libraryOf(m) }))
|
|
942
|
+
: rows.map((m) => ({ path: m.path, tag: m.tag, caption: m.caption, library: libraryOf(m) }))
|
|
943
|
+
}
|
|
944
|
+
const howToSend = textMode
|
|
945
|
+
? '发图:当前发送方式是「纯文字」,不发图片——不要写 [表情: ...] 或 [任何描述] 这类方括号标记,不要调用 dsh_im_return_file,也不要把图片路径贴进回复;把下面某一行「描述=」的原文用进你的文字回复里,接梗/吐槽/卖萌即可。'
|
|
946
|
+
: (imageMode ? '当前发送方式是「图片」:挑好图就必须真的发出去,不能只写文字描述。' : '') +
|
|
947
|
+
(imMode
|
|
948
|
+
? '发图:把挑中的那一行 path 原样传给 dsh_im_return_file(path=...)——它会作为 ' + imLabel +
|
|
949
|
+
' 原生图片消息发出;不用等用户要求,现在就能主动发。回复正文只写普通文字:不要写 [表情: ...] 或 [任何描述] 这类方括号标记,不要写 markdown 图片或把本地路径贴进回复,也不用解释图片投递过程——图片会由渠道自己发出。'
|
|
950
|
+
: webMode
|
|
951
|
+
? '发图:把下面某一行的 [表情: ...] 整段原样写进回复(描述抄候选原文,可加一两句文字,不要加网址)。候选 JSON 里的 path/library 只是出处信息,用户问「这图哪个库的/文件叫什么」可以引用;发图仍然只写 [表情: 描述],不要把路径贴进回复。'
|
|
952
|
+
: '用 send + path 发出。')
|
|
953
|
+
|
|
954
|
+
// 关键词优先:有关键词就先精确搜(caption/关键词/图名),命中了直接给候选。
|
|
955
|
+
// 全都没命中才退回老路——拿 query 推断情绪随机抽,并在消息里说清是退回来的。
|
|
956
|
+
let keywordMiss = ''
|
|
957
|
+
if (query) {
|
|
958
|
+
const found = memes.search(query, limit, tag)
|
|
959
|
+
if (found.memes.length > 0) {
|
|
960
|
+
return {
|
|
961
|
+
ok: true,
|
|
962
|
+
mode: 'keyword',
|
|
963
|
+
query: found.query,
|
|
964
|
+
hits: hits(found.memes),
|
|
965
|
+
tags: found.tags,
|
|
966
|
+
message: '关键词「' + found.query + '」命中 ' + found.memes.length + ' 张' +
|
|
967
|
+
(tag ? '(限在情绪 ' + tag + ' 里)' : '') +
|
|
968
|
+
'。看 caption 贴就发;不满意再 search(换词或加大 limit)。' +
|
|
969
|
+
howToSend + '\n' + lines(found.memes).join('\n'),
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
if (found.reason) return { ok: false, message: found.reason }
|
|
973
|
+
keywordMiss = '关键词「' + (found.query || query) + '」没找到图(caption/关键词里没有这几个词)。'
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
const { mood, memes: candidates, tags, reason } = memes.sampleMood(tag, query, limit)
|
|
977
|
+
if (!mood) {
|
|
978
|
+
return {
|
|
979
|
+
ok: false,
|
|
980
|
+
// 换词建议给真实的分类统计(按张数),比静态情绪字典有用得多(issue #53)
|
|
981
|
+
message: reason || (keywordMiss + ' 要么换个更常见的词,要么给个情绪 tag。' + tagHint()),
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
if (candidates.length === 0) {
|
|
985
|
+
return {
|
|
986
|
+
ok: false,
|
|
987
|
+
// 没有可用图库时 sampler 会给 reason,直说比「情绪下没有图」清楚
|
|
988
|
+
message: reason || (keywordMiss + '情绪「' + mood + '」下也没有图。换一个: ' + tagHint()),
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
return {
|
|
992
|
+
ok: true,
|
|
993
|
+
mode: 'mood',
|
|
994
|
+
mood,
|
|
995
|
+
hits: hits(candidates),
|
|
996
|
+
tags,
|
|
997
|
+
message: (keywordMiss ? keywordMiss + '下面按情绪抽:' : '') +
|
|
998
|
+
'情绪 ' + mood + ' 随机 ' + candidates.length + ' 张。看 caption 贴就发;不满意再 search 同一 tag 换一批(可加大 limit)。' +
|
|
999
|
+
howToSend + '\n' + lines(candidates).join('\n'),
|
|
1000
|
+
}
|
|
1001
|
+
},
|
|
1002
|
+
}))
|
|
1003
|
+
}
|