dsh-chat-comprehension 0.3.7 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +73 -27
- package/client.js +441 -53
- package/lib/engines.mjs +174 -7
- package/lib/index.js +316 -35
- package/lib/models.mjs +166 -0
- package/lib/qq-cards.mjs +16 -8
- package/lib/qqbot-0.5.3-patches.json +60 -4
- package/lib/qqbot-patch.mjs +1 -1
- package/lib/video.mjs +1 -1
- package/package.json +2 -2
- package/vendor/dsh-agent-md/lib/chat-persona.js +29 -4
- package/vendor/dsh-agent-md/lib/index.js +80 -8
- package/vendor/dsh-agent-md/lib/qq.js +288 -44
- package/vendor/dsh-bili-scroll/index.js +25 -9
- package/vendor/dsh-meme/index.js +2 -2
- package/vendor/dsh-meme/memes.js +3 -1
- package/vendor/dsh-world/lib/qqScope.js +65 -17
- package/vendor/dsh-world/lib/runtime.js +17 -5
package/lib/models.mjs
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* models.mjs —— 在插件里看 / 改每个模型的「输入类型」(文字 / 图片),写回 DSH 自己的模型配置。
|
|
3
|
+
*
|
|
4
|
+
* 不碰 cordis.patch.yml 文本:走宿主的 settings 服务(和 DSH「设置 → 模型」页同一条路),
|
|
5
|
+
* 它会校验、加锁、原子写、即时生效,失败自动回滚。DSH 判断「这个模型能不能看图」读的就是这份声明,
|
|
6
|
+
* 所以改完以后 DSH 里这个模型的说明(支持的输入)就跟着变。
|
|
7
|
+
*
|
|
8
|
+
* 写到哪里由路由自己决定(llm.listConfigurableProviders() 给出 settingsNs / settingsPath):
|
|
9
|
+
* - 有 `models` 列表的路由(pi-ai 自建网关、DeepSeek 自建目录):models[i].input / inputModalities
|
|
10
|
+
* - 没有 `models` 列表、只有 `modelOverrides` 的路由(pi-ai 自带目录、DeepSeek 账号):modelOverrides[id].…
|
|
11
|
+
* 字段名:pi-ai 用 `input`,DeepSeek 系用 `inputModalities`(看路由现有条目 / 配置结构判断)。
|
|
12
|
+
* DeepSeek 系的条目还支持 `description`:顺手写一句「支持图片输入 / 只支持文字」。
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const MODALITIES = ['text', 'image']
|
|
16
|
+
|
|
17
|
+
function cleanInput(list) {
|
|
18
|
+
const set = new Set((Array.isArray(list) ? list : []).filter((m) => MODALITIES.includes(m)))
|
|
19
|
+
set.add('text')
|
|
20
|
+
return MODALITIES.filter((m) => set.has(m))
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function getPath(root, path) {
|
|
24
|
+
let cur = root
|
|
25
|
+
for (const key of path) {
|
|
26
|
+
if (cur === null || cur === undefined || typeof cur !== 'object') return undefined
|
|
27
|
+
cur = cur[key]
|
|
28
|
+
}
|
|
29
|
+
return cur
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** 这个路由的模型字段叫 input(pi-ai)还是 inputModalities(DeepSeek 系)。 */
|
|
33
|
+
function fieldFor(profile, ns) {
|
|
34
|
+
const rows = Array.isArray(profile && profile.models) ? profile.models : []
|
|
35
|
+
for (const row of rows) {
|
|
36
|
+
if (row && Object.hasOwn(row, 'inputModalities')) return 'inputModalities'
|
|
37
|
+
if (row && Object.hasOwn(row, 'input')) return 'input'
|
|
38
|
+
}
|
|
39
|
+
const overrides = profile && typeof profile.modelOverrides === 'object' && profile.modelOverrides !== null ? Object.values(profile.modelOverrides) : []
|
|
40
|
+
for (const row of overrides) {
|
|
41
|
+
if (row && Object.hasOwn(row, 'inputModalities')) return 'inputModalities'
|
|
42
|
+
if (row && Object.hasOwn(row, 'input')) return 'input'
|
|
43
|
+
}
|
|
44
|
+
return /deepseek/i.test(String(ns)) ? 'inputModalities' : 'input'
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* 算出要写的 settings ops。纯函数,便于测试。
|
|
49
|
+
* @param {{ ns: string, path: string[], profile: object, modelId: string, input?: string[], reset?: boolean, describe?: boolean }} plan
|
|
50
|
+
* @returns {{ ops: Array<{op:'set'|'unset', path:string[], value?:unknown}>, field: string, where: string }}
|
|
51
|
+
*/
|
|
52
|
+
export function planInputOps({ ns, path, profile, modelId, input, reset = false, describe = true }) {
|
|
53
|
+
const field = fieldFor(profile, ns)
|
|
54
|
+
const value = cleanInput(input)
|
|
55
|
+
const rows = Array.isArray(profile && profile.models) ? profile.models : null
|
|
56
|
+
const deepseek = field === 'inputModalities'
|
|
57
|
+
const note = value.includes('image') ? '支持图片输入(文字 + 图片)' : '只支持文字输入'
|
|
58
|
+
const ops = []
|
|
59
|
+
if (rows) {
|
|
60
|
+
const index = rows.findIndex((row) => row && row.id === modelId)
|
|
61
|
+
if (index < 0) throw Object.assign(new Error(`路由 ${ns} 的 models 里没有 ${modelId};先在 DSH「设置 → 模型」里把它加进来`), { status: 400 })
|
|
62
|
+
const base = [...path, 'models', String(index)]
|
|
63
|
+
if (reset) {
|
|
64
|
+
ops.push({ op: 'unset', path: [...base, field] })
|
|
65
|
+
if (deepseek && typeof rows[index].description === 'string' && /^(支持图片输入|只支持文字输入)/.test(rows[index].description)) ops.push({ op: 'unset', path: [...base, 'description'] })
|
|
66
|
+
} else {
|
|
67
|
+
ops.push({ op: 'set', path: [...base, field], value })
|
|
68
|
+
// DeepSeek 自建目录的条目有 description:没写过、或者是我们以前写的那句,才替换
|
|
69
|
+
if (deepseek && describe && (rows[index].description === undefined || /^(支持图片输入|只支持文字输入)/.test(String(rows[index].description)))) {
|
|
70
|
+
ops.push({ op: 'set', path: [...base, 'description'], value: note })
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return { ops, field, where: `${ns}:${base.join('.')}.${field}` }
|
|
74
|
+
}
|
|
75
|
+
const overrides = profile && typeof profile.modelOverrides === 'object' && profile.modelOverrides !== null ? profile.modelOverrides : {}
|
|
76
|
+
const base = [...path, 'modelOverrides', modelId]
|
|
77
|
+
if (reset) {
|
|
78
|
+
const current = overrides[modelId]
|
|
79
|
+
const keys = current && typeof current === 'object' ? Object.keys(current) : []
|
|
80
|
+
// 这条 override 只剩输入类型(和我们写的说明)⇒ 整条删掉;还有别的字段 ⇒ 只删输入类型
|
|
81
|
+
if (keys.every((k) => k === field || (k === 'description' && /^(支持图片输入|只支持文字输入)/.test(String(current.description))))) {
|
|
82
|
+
ops.push({ op: 'unset', path: base })
|
|
83
|
+
// 这条 override 本来就是我们建的:删完 modelOverrides 空了,把空壳也清掉,别在设置里留个 `{}`
|
|
84
|
+
if (keys.length > 0 && Object.keys(overrides).length === 1) ops.push({ op: 'unset', path: [...path, 'modelOverrides'] })
|
|
85
|
+
} else ops.push({ op: 'unset', path: [...base, field] })
|
|
86
|
+
} else {
|
|
87
|
+
ops.push({ op: 'set', path: [...base, field], value })
|
|
88
|
+
}
|
|
89
|
+
return { ops, field, where: `${ns}:${base.join('.')}.${field}` }
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* 列出所有模型和它们的输入类型(给页面)。
|
|
94
|
+
* @returns {Promise<{ providers: Array<{ id, label, configurable, models: Array<{ id, label, input: string[]|null, declared: boolean }> }> }>}
|
|
95
|
+
*/
|
|
96
|
+
export async function listModelCapabilities(ctx) {
|
|
97
|
+
const llm = typeof ctx.get === 'function' ? ctx.get('llm') : null
|
|
98
|
+
if (!llm || typeof llm.listProviders !== 'function') return { providers: [] }
|
|
99
|
+
const settings = typeof ctx.get === 'function' ? ctx.get('settings') : null
|
|
100
|
+
const configurable = new Map()
|
|
101
|
+
try {
|
|
102
|
+
for (const entry of (typeof llm.listConfigurableProviders === 'function' ? llm.listConfigurableProviders() : [])) configurable.set(entry.provider, entry)
|
|
103
|
+
} catch { /* 老宿主 */ }
|
|
104
|
+
let docs = []
|
|
105
|
+
try { docs = settings && typeof settings.describe === 'function' ? settings.describe({ redactSecrets: true }) : [] } catch { docs = [] }
|
|
106
|
+
const providers = []
|
|
107
|
+
for (const p of llm.listProviders()) {
|
|
108
|
+
const id = p.id || p.provider || p.name || ''
|
|
109
|
+
if (!id) continue
|
|
110
|
+
let models = []
|
|
111
|
+
try { models = await llm.listModels(id) } catch { models = [] }
|
|
112
|
+
const entry = configurable.get(id)
|
|
113
|
+
const doc = entry ? docs.find((d) => d.ns === entry.settingsNs) : null
|
|
114
|
+
const profile = doc ? getPath(doc.value, entry.settingsPath) : null
|
|
115
|
+
const field = entry ? fieldFor(profile, entry.settingsNs) : 'input'
|
|
116
|
+
const declaredOf = (modelId) => {
|
|
117
|
+
if (!profile || typeof profile !== 'object') return false
|
|
118
|
+
const row = Array.isArray(profile.models) ? profile.models.find((m) => m && m.id === modelId) : (profile.modelOverrides && profile.modelOverrides[modelId])
|
|
119
|
+
return Boolean(row && Array.isArray(row[field]) && row[field].length > 0)
|
|
120
|
+
}
|
|
121
|
+
providers.push({
|
|
122
|
+
id,
|
|
123
|
+
label: p.label || p.displayName || p.name || id,
|
|
124
|
+
configurable: Boolean(entry && profile && typeof profile === 'object'),
|
|
125
|
+
models: (Array.isArray(models) ? models : []).map((m) => ({
|
|
126
|
+
id: m.id || m.model || '',
|
|
127
|
+
label: m.name || m.label || m.id || '',
|
|
128
|
+
input: Array.isArray(m.inputModalities) ? m.inputModalities : null,
|
|
129
|
+
declared: declaredOf(m.id || m.model || ''),
|
|
130
|
+
...(typeof m.description === 'string' ? { description: m.description } : {}),
|
|
131
|
+
})).filter((m) => m.id !== ''),
|
|
132
|
+
})
|
|
133
|
+
}
|
|
134
|
+
return { providers }
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** 改一个模型的输入类型(或恢复默认)。 */
|
|
138
|
+
export async function setModelInput(ctx, { provider, model, input, reset = false }) {
|
|
139
|
+
const llm = typeof ctx.get === 'function' ? ctx.get('llm') : null
|
|
140
|
+
const settings = typeof ctx.get === 'function' ? ctx.get('settings') : null
|
|
141
|
+
if (!llm || !settings || typeof settings.mutate !== 'function' || typeof settings.describe !== 'function') {
|
|
142
|
+
throw Object.assign(new Error('这个 DSH 版本没有可写的设置服务;请到 DSH「设置 → 模型」里改'), { status: 501 })
|
|
143
|
+
}
|
|
144
|
+
const entry = (typeof llm.listConfigurableProviders === 'function' ? llm.listConfigurableProviders() : []).find((e) => e.provider === provider)
|
|
145
|
+
if (!entry) throw Object.assign(new Error(`模型服务 ${provider} 不能在插件里改(不是配置出来的路由)`), { status: 400 })
|
|
146
|
+
const doc = settings.describe({ redactSecrets: true }).find((d) => d.ns === entry.settingsNs)
|
|
147
|
+
if (!doc) throw Object.assign(new Error(`找不到 ${entry.settingsNs} 的设置`), { status: 400 })
|
|
148
|
+
const profile = getPath(doc.value, entry.settingsPath) || {}
|
|
149
|
+
const plan = planInputOps({ ns: entry.settingsNs, path: [...entry.settingsPath], profile, modelId: model, input, reset })
|
|
150
|
+
try {
|
|
151
|
+
await settings.mutate(entry.settingsNs, plan.ops, doc.revision)
|
|
152
|
+
} catch (error) {
|
|
153
|
+
// 别处刚改过设置:让页面刷新重来,别把「设置冲突」当成上游 502
|
|
154
|
+
if (error && error.code === 'SETTINGS_CONFLICT') {
|
|
155
|
+
throw Object.assign(new Error('设置刚被别处改过,刷新页面后再试一次'), { status: 409, code: 'settings-conflict' })
|
|
156
|
+
}
|
|
157
|
+
throw error
|
|
158
|
+
}
|
|
159
|
+
// 读回宿主现在认的输入类型,确认真的生效
|
|
160
|
+
let effective = null
|
|
161
|
+
try {
|
|
162
|
+
const info = typeof llm.resolveModelInfo === 'function' ? await llm.resolveModelInfo(provider, model) : null
|
|
163
|
+
effective = info && Array.isArray(info.inputModalities) ? info.inputModalities : null
|
|
164
|
+
} catch { effective = null }
|
|
165
|
+
return { ok: true, where: plan.where, field: plan.field, ops: plan.ops.length, effective }
|
|
166
|
+
}
|
package/lib/qq-cards.mjs
CHANGED
|
@@ -211,7 +211,12 @@ export async function expandCards(message, opts = {}) {
|
|
|
211
211
|
const contentText = String((message && message.content) || '')
|
|
212
212
|
const sources = collectSources(message)
|
|
213
213
|
const arks = findArks(message)
|
|
214
|
-
|
|
214
|
+
// 群里常见的是「回复那张卡片 + @机器人」:卡片本身只在引用(msg_elements)里,正文只有一句 @
|
|
215
|
+
const quotedText = sources.filter((x) => x.where === 'msg_elements.content').map((x) => x.value).join('\n')
|
|
216
|
+
const CARD_RE = /\[卡片消息\]|小程序|\[分享\]|\[链接\]|ark/i
|
|
217
|
+
const quoted = CARD_RE.test(quotedText)
|
|
218
|
+
const cardish = CARD_RE.test(contentText) || quoted || arks.length > 0
|
|
219
|
+
const isBiliCard = /哔哩哔哩|bilibili|b站|b23\.tv/i.test(contentText + '\n' + quotedText) || arks.some((a) => parseArk(a).isBili)
|
|
215
220
|
|
|
216
221
|
// 从所有来源里捞 URL / BV(卡片正文、message_scene.ext、msg_elements…)
|
|
217
222
|
const urls = []
|
|
@@ -226,7 +231,10 @@ export async function expandCards(message, opts = {}) {
|
|
|
226
231
|
for (const u of card.urls) { urls.push(u); urlOf.push({ url: u, where: 'ark' }) }
|
|
227
232
|
if (!bvid && card.bvid) bvid = card.bvid
|
|
228
233
|
}
|
|
229
|
-
|
|
234
|
+
// 卡片里的封面图 / 图标地址不算「链接」:只留可能指向视频的地址
|
|
235
|
+
const IMAGE_HOSTS = /(^|\.)(ugcimg\.cn|gtimg\.cn|qpic\.cn|qlogo\.cn|nt\.qq\.com\.cn|hdslb\.com)$/i
|
|
236
|
+
const linkish = (u) => { try { const h = new URL(u).hostname; return !IMAGE_HOSTS.test(h) && !/\.(png|jpe?g|gif|webp)(\?|$)/i.test(u) } catch { return false } }
|
|
237
|
+
const uniq = [...new Set(urls)].filter(linkish)
|
|
230
238
|
|
|
231
239
|
if (uniq.length === 0 && bvid === '' && !cardish) return null
|
|
232
240
|
|
|
@@ -261,15 +269,15 @@ export async function expandCards(message, opts = {}) {
|
|
|
261
269
|
lines.push('[QQ 分享卡片] 哔哩哔哩' + (title ? ':《' + title + '》' : '') + '\n视频链接:' + videoUrl
|
|
262
270
|
+ (opts.storyboard ? '\n(这是对方分享的 B站 视频;要看画面和台词,直接用 video_storyboard 打开这个链接,不需要再向对方要 BV 号。)' : ''))
|
|
263
271
|
} else if (cardish) {
|
|
264
|
-
//
|
|
272
|
+
// 卡片在,但真的没有链接:说清楚,别让模型去猜标题(用户选的是「只认链接,不按标题搜」)
|
|
265
273
|
const title = (() => {
|
|
266
274
|
for (const ark of arks) { const t = clip(parseArk(ark).title); if (t) return t }
|
|
267
|
-
const
|
|
268
|
-
return
|
|
275
|
+
const m = (quotedText + '\n' + contentText).match(/title:\s*([^\n]+)/i) || (quotedText + '\n' + contentText).match(/摘要:\s*(?:\[QQ小程序\])?([^\n]+)/)
|
|
276
|
+
return m ? clip(m[1]) : ''
|
|
269
277
|
})()
|
|
270
|
-
results.push({ kind: 'card-no-link', title, sources: uniq.slice(0, 5), where: sources.map((x) => x.where) })
|
|
271
|
-
lines.push('[QQ 分享卡片]' + (title ? ':' + title : '')
|
|
272
|
-
+ '\n
|
|
278
|
+
results.push({ kind: 'card-no-link', bili: isBiliCard, quoted, title, sources: uniq.slice(0, 5), where: sources.map((x) => x.where) })
|
|
279
|
+
lines.push('[QQ 分享卡片]' + (isBiliCard ? ' 哔哩哔哩' : '') + (title && !/^(哔哩哔哩|bilibili)$/i.test(title) ? ':' + title : '') + (quoted ? '(对方引用的那张)' : '')
|
|
280
|
+
+ '\n(QQ 发来的这张卡片里没有视频链接或 BV 号,打不开。请对方把 b23.tv 链接或 BV 号直接打字发过来;不要按标题去搜、也不要猜视频内容。)')
|
|
273
281
|
}
|
|
274
282
|
|
|
275
283
|
if (opts.captureFile) {
|
|
@@ -57,8 +57,29 @@
|
|
|
57
57
|
},
|
|
58
58
|
{
|
|
59
59
|
"group": "v4",
|
|
60
|
-
"old":
|
|
61
|
-
|
|
60
|
+
"old": [
|
|
61
|
+
" async sendImage(path, caption) {\n if (!botReady) throw new Error('QQ 通道未就绪');\n const target = latestReplyTarget();\n if (!target) throw new Error('还没有 QQ 聊天目标');\n return bot.sendImage(resolveReplyTarget(target, replyLimiter, false), { localPath: String(path) }, caption ? { content: String(caption) } : undefined);\n },\n async sendVoice(path) {\n if (!botReady) throw new Error('QQ 通道未就绪');\n const target = latestReplyTarget();\n if (!target) throw new Error('还没有 QQ 聊天目标');\n return bot.sendVoice(resolveReplyTarget(target, replyLimiter, false), { localPath: String(path) });\n },",
|
|
62
|
+
" // ⚠️ 这两个绝不能 reject:调用方(dsh-meme 的 send_meme)用的是同步 try/catch,\n // 拿到的 rejected Promise 没人接 ⇒ 宿主 unhandledRejection ⇒ \"fatal load failure\" ⇒ 进程退出。\n // 统一改成「永远 resolve,失败返回 { ok:false, error }」。\n async sendImage(path, caption) {\n try {\n if (!botReady) return { ok: false, error: 'QQ 通道未就绪' };\n const target = latestReplyTarget();\n if (!target) return { ok: false, error: '还没有 QQ 聊天目标(先在 QQ 里给机器人发一条消息)' };\n await bot.sendImage(resolveReplyTarget(target, replyLimiter, false), { localPath: String(path) }, caption ? { content: String(caption) } : undefined);\n return { ok: true };\n } catch (err) {\n logger.warn(`im-qqbot: sendImage 失败(已兜住):${err instanceof Error ? err.message : String(err)}`);\n return { ok: false, error: err instanceof Error ? err.message : String(err) };\n }\n },\n async sendVoice(path) {\n try {\n if (!botReady) return { ok: false, error: 'QQ 通道未就绪' };\n const target = latestReplyTarget();\n if (!target) return { ok: false, error: '还没有 QQ 聊天目标(先在 QQ 里给机器人发一条消息)' };\n await bot.sendVoice(resolveReplyTarget(target, replyLimiter, false), { localPath: String(path) });\n return { ok: true };\n } catch (err) {\n logger.warn(`im-qqbot: sendVoice 失败(已兜住):${err instanceof Error ? err.message : String(err)}`);\n return { ok: false, error: err instanceof Error ? err.message : String(err) };\n }\n },"
|
|
63
|
+
],
|
|
64
|
+
"new": [
|
|
65
|
+
" // ⚠️ 这两个绝不能 reject:调用方(dsh-meme 的 send_meme)用的是同步 try/catch,\n // 拿到的 rejected Promise 没人接 ⇒ 宿主 unhandledRejection ⇒ \"fatal load failure\" ⇒ 进程退出。\n // 统一改成「永远 resolve,失败返回 { ok:false, error }」。\n async sendImage(path, caption, opts) {\n try {\n if (!botReady) return { ok: false, error: 'QQ 通道未就绪' };\n const target = replyTargetFor(opts);\n if (!target) return { ok: false, error: '还没有 QQ 聊天目标(先在 QQ 里给机器人发一条消息)' };\n await bot.sendImage(resolveReplyTarget(target, replyLimiter, false), { localPath: String(path) }, caption ? { content: String(caption) } : undefined);\n return { ok: true };\n } catch (err) {\n logger.warn(`im-qqbot: sendImage 失败(已兜住):${err instanceof Error ? err.message : String(err)}`);\n return { ok: false, error: err instanceof Error ? err.message : String(err) };\n }\n },\n async sendVoice(path, opts) {\n try {\n if (!botReady) return { ok: false, error: 'QQ 通道未就绪' };\n const target = replyTargetFor(opts);\n if (!target) return { ok: false, error: '还没有 QQ 聊天目标(先在 QQ 里给机器人发一条消息)' };\n await bot.sendVoice(resolveReplyTarget(target, replyLimiter, false), { localPath: String(path) });\n return { ok: true };\n } catch (err) {\n logger.warn(`im-qqbot: sendVoice 失败(已兜住):${err instanceof Error ? err.message : String(err)}`);\n return { ok: false, error: err instanceof Error ? err.message : String(err) };\n }\n },",
|
|
66
|
+
" // ⚠️ 这两个绝不能 reject:调用方(dsh-meme 的 send_meme)用的是同步 try/catch,\n // 拿到的 rejected Promise 没人接 ⇒ 宿主 unhandledRejection ⇒ \"fatal load failure\" ⇒ 进程退出。\n // 统一改成「永远 resolve,失败返回 { ok:false, error }」。\n async sendImage(path, caption, opts) {\n try {\n if (!botReady) return { ok: false, error: 'QQ 通道未就绪' };\n const target = replyTargetFor(opts);\n if (!target) return { ok: false, error: '还没有 QQ 聊天目标(先在 QQ 里给机器人发一条消息)' };\n await bot.sendImage(resolveReplyTarget(target, replyLimiter, false), { localPath: String(path) }, caption ? { content: String(caption) } : undefined);\n return { ok: true };\n } catch (err) {\n logger.warn(`im-qqbot: sendImage 失败(已兜住):${err instanceof Error ? err.message : String(err)}`);\n return { ok: false, error: err instanceof Error ? err.message : String(err) };\n }\n },\n async sendVoice(path, opts) {\n try {\n if (!botReady) return { ok: false, error: 'QQ 通道未就绪' };\n const target = replyTargetFor(opts);\n if (!target) return { ok: false, error: '还没有 QQ 聊天目标(先在 QQ 里给机器人发一条消息)' };\n await bot.sendVoice(resolveReplyTarget(target, replyLimiter, false), { localPath: String(path) });\n return { ok: true };\n } catch (err) {\n logger.warn(`im-qqbot: sendVoice 失败(已兜住):${err instanceof Error ? err.message : String(err)}`);\n return { ok: false, error: err instanceof Error ? err.message : String(err) };\n }\n },"
|
|
67
|
+
]
|
|
68
|
+
},
|
|
69
|
+
{
|
|
70
|
+
"group": "v4",
|
|
71
|
+
"old": " const latestReplyTarget = () => {\n let best = null;",
|
|
72
|
+
"new": " // companion-patch:v4 target —— 调用方带了 sessionId 就发回那个会话;没有才退回「最近活跃」\n const replyTargetFor = (opts) => {\n const sid = opts && typeof opts === 'object' && opts.sessionId ? String(opts.sessionId) : '';\n if (sid) {\n const record = manager.findBySessionId(sid);\n if (record && record.replyTarget) return record.replyTarget;\n }\n return latestReplyTarget();\n };\n const latestReplyTarget = () => {\n let best = null;"
|
|
73
|
+
},
|
|
74
|
+
{
|
|
75
|
+
"group": "v6",
|
|
76
|
+
"old": " if (typeof ctx.provide === 'function') {",
|
|
77
|
+
"new": " // companion-patch:v6 default-model —— 只给 QQ 会话读的「默认模型」,不影响 DSH 全局默认\n const companionDefaultRoute = () => {\n try {\n if (typeof process.getBuiltinModule !== 'function') return null;\n const fs = process.getBuiltinModule('node:fs');\n const os = process.getBuiltinModule('node:os');\n const path = process.getBuiltinModule('node:path');\n const home = process.env.DSH_HOME || path.join(os.homedir(), '.dsh');\n const raw = JSON.parse(fs.readFileSync(path.join(home, 'agents', 'companion-model.json'), 'utf8'));\n const provider = String((raw && raw.provider) || '').trim();\n const model = String((raw && raw.model) || '').trim();\n if (!provider || !model) return null;\n const reasoningEffort = String((raw && raw.reasoningEffort) || '').trim();\n return { provider, model, ...(reasoningEffort ? { reasoningEffort } : {}) };\n } catch { return null; }\n };\n if (typeof ctx.provide === 'function') {"
|
|
78
|
+
},
|
|
79
|
+
{
|
|
80
|
+
"group": "v6",
|
|
81
|
+
"old": " async sendVoice(path, opts) {\n try {\n if (!botReady) return { ok: false, error: 'QQ 通道未就绪' };\n const target = replyTargetFor(opts);\n if (!target) return { ok: false, error: '还没有 QQ 聊天目标(先在 QQ 里给机器人发一条消息)' };\n await bot.sendVoice(resolveReplyTarget(target, replyLimiter, false), { localPath: String(path) });\n return { ok: true };\n } catch (err) {\n logger.warn(`im-qqbot: sendVoice 失败(已兜住):${err instanceof Error ? err.message : String(err)}`);\n return { ok: false, error: err instanceof Error ? err.message : String(err) };\n }\n },\n",
|
|
82
|
+
"new": " async sendVoice(path, opts) {\n try {\n if (!botReady) return { ok: false, error: 'QQ 通道未就绪' };\n const target = replyTargetFor(opts);\n if (!target) return { ok: false, error: '还没有 QQ 聊天目标(先在 QQ 里给机器人发一条消息)' };\n await bot.sendVoice(resolveReplyTarget(target, replyLimiter, false), { localPath: String(path) });\n return { ok: true };\n } catch (err) {\n logger.warn(`im-qqbot: sendVoice 失败(已兜住):${err instanceof Error ? err.message : String(err)}`);\n return { ok: false, error: err instanceof Error ? err.message : String(err) };\n }\n },\n\n // companion-patch:v6 sessions —— 人格 / 工作区改动立刻生效:有活会话就 fork 到新目录(保留历史),\n // 没有活会话就换一个新 sessionId,下一条消息按新配置重建。\n async resetSession(peerKey) {\n try {\n const parts = String(peerKey || '').split(':');\n if (parts.length < 4 || parts[0] !== 'qqbot') return { ok: false, error: '不是 QQ 会话 key' };\n const key = String(peerKey);\n const scope = parts[2];\n const peerId = parts.slice(3).join(':');\n const record = typeof manager.getSessionRecord === 'function' ? manager.getSessionRecord(scope, peerId) : undefined;\n if (record) {\n await manager.rebuildSession(record, {});\n return { ok: true, rebuilt: true, sessionId: record.sessionId };\n }\n const fresh = String(manager.deriveSessionId(key + ':reset:' + Date.now()));\n manager.modelResolver.setSessionId(key, fresh);\n return { ok: true, rebuilt: false, sessionId: fresh };\n } catch (err) {\n logger.warn(`im-qqbot: resetSession 失败(已兜住):${err instanceof Error ? err.message : String(err)}`);\n return { ok: false, error: err instanceof Error ? err.message : String(err) };\n }\n },\n // companion-patch:v6 default-model —— 默认模型改完,正开着的 QQ 会话也立刻切(有单独指定模型的不动)\n async applyDefaultModel() {\n try {\n const route = companionDefaultRoute();\n if (!route) return { ok: false, error: '还没有设置 QQ 默认模型' };\n let changed = 0;\n for (const record of manager.sessions.values()) {\n if (!record || !record.agent || !record.agent.model || typeof record.agent.model.select !== 'function') continue;\n if (typeof manager.modelResolver.hasOverride === 'function' && manager.modelResolver.hasOverride(record.sessionKey)) continue;\n record.agent.model.select(route);\n changed += 1;\n }\n return { ok: true, changed };\n } catch (err) {\n logger.warn(`im-qqbot: applyDefaultModel 失败(已兜住):${err instanceof Error ? err.message : String(err)}`);\n return { ok: false, error: err instanceof Error ? err.message : String(err) };\n }\n },\n"
|
|
62
83
|
}
|
|
63
84
|
]
|
|
64
85
|
},
|
|
@@ -109,6 +130,41 @@
|
|
|
109
130
|
" cwd: companionWorkspace(key) || this.config.cwd || process.cwd(),",
|
|
110
131
|
" cwd: companionWorkspace(key) || this.workspaceDir(),"
|
|
111
132
|
]
|
|
133
|
+
},
|
|
134
|
+
{
|
|
135
|
+
"group": "v4",
|
|
136
|
+
"old": "/** dsh-chat-comprehension:按 QQ 会话(peerKey)指定工作区;没配就返回空串 */\nfunction companionWorkspace(peerKey) {\n try {\n if (typeof process.getBuiltinModule !== 'function') return '';\n const fs = process.getBuiltinModule('node:fs');\n const os = process.getBuiltinModule('node:os');\n const path = process.getBuiltinModule('node:path');\n const home = process.env.DSH_HOME || path.join(os.homedir(), '.dsh');\n const map = JSON.parse(fs.readFileSync(path.join(home, 'agents', 'chat-workspaces.json'), 'utf8'));\n const value = typeof peerKey === 'string' ? map[peerKey] : '';\n return typeof value === 'string' ? value : '';\n }\n catch {\n return '';\n }\n}\nexport class SessionManager {",
|
|
137
|
+
"new": "/** dsh-chat-comprehension:记下「哪个 QQ 聊天 → 哪个 DSH 会话」(每个聊天各记各的记忆、人格、模型都靠它) */\nfunction companionRecordPeer(peerKey, sessionId, previous) {\n try {\n if (typeof process.getBuiltinModule !== 'function' || !peerKey || !sessionId) return;\n const fs = process.getBuiltinModule('node:fs');\n const os = process.getBuiltinModule('node:os');\n const path = process.getBuiltinModule('node:path');\n const home = process.env.DSH_HOME || path.join(os.homedir(), '.dsh');\n const file = path.join(home, 'agents', 'qq-peers.json');\n let data = {};\n try { data = JSON.parse(fs.readFileSync(file, 'utf8')) || {}; } catch { data = {}; }\n const peers = data.peers && typeof data.peers === 'object' ? data.peers : {};\n const row = peers[peerKey] && typeof peers[peerKey] === 'object' ? peers[peerKey] : { sessions: [] };\n const sessions = Array.isArray(row.sessions) ? row.sessions.filter((x) => typeof x === 'string') : [];\n for (const id of [String(sessionId), previous ? String(previous) : '']) {\n if (id && !sessions.includes(id)) sessions.unshift(id);\n }\n if (row.current === String(sessionId) && sessions.length === (row.sessions || []).length) return;\n peers[peerKey] = { current: String(sessionId), sessions: sessions.slice(0, 30), updatedAt: new Date().toISOString() };\n fs.mkdirSync(path.dirname(file), { recursive: true });\n const tmp = file + '.' + process.pid + '.tmp';\n fs.writeFileSync(tmp, JSON.stringify({ version: 1, peers }, null, 2) + '\\n', 'utf8');\n fs.renameSync(tmp, file);\n }\n catch { /* 记不下来不能拦住消息 */ }\n}\n/** dsh-chat-comprehension:按 QQ 会话(peerKey)指定工作区;没配就返回空串 */\nfunction companionWorkspace(peerKey) {\n try {\n if (typeof process.getBuiltinModule !== 'function') return '';\n const fs = process.getBuiltinModule('node:fs');\n const os = process.getBuiltinModule('node:os');\n const path = process.getBuiltinModule('node:path');\n const home = process.env.DSH_HOME || path.join(os.homedir(), '.dsh');\n const map = JSON.parse(fs.readFileSync(path.join(home, 'agents', 'chat-workspaces.json'), 'utf8'));\n const value = typeof peerKey === 'string' ? map[peerKey] : '';\n return typeof value === 'string' ? value : '';\n }\n catch {\n return '';\n }\n}\nexport class SessionManager {"
|
|
138
|
+
},
|
|
139
|
+
{
|
|
140
|
+
"group": "v4",
|
|
141
|
+
"old": " this.sessions.set(key, record);\n return record;\n }",
|
|
142
|
+
"new": " this.sessions.set(key, record);\n companionRecordPeer(key, sessionId); // companion-patch:v4 peers\n return record;\n }"
|
|
143
|
+
},
|
|
144
|
+
{
|
|
145
|
+
"group": "v4",
|
|
146
|
+
"old": " this.modelResolver.setSessionId(key, childId);",
|
|
147
|
+
"new": " this.modelResolver.setSessionId(key, childId);\n companionRecordPeer(key, childId, record.sessionId); // companion-patch:v4 peers"
|
|
148
|
+
}
|
|
149
|
+
]
|
|
150
|
+
},
|
|
151
|
+
{
|
|
152
|
+
"file": "model/model-resolver.js",
|
|
153
|
+
"steps": [
|
|
154
|
+
{
|
|
155
|
+
"group": "v6",
|
|
156
|
+
"old": "export class ModelResolver {",
|
|
157
|
+
"new": "/** dsh-chat-comprehension:QQ 默认模型(只给 QQ 网关建的会话用,不碰 DSH 全局默认) */\nfunction companionDefaultModel() {\n try {\n if (typeof process.getBuiltinModule !== 'function') return null;\n const fs = process.getBuiltinModule('node:fs');\n const os = process.getBuiltinModule('node:os');\n const path = process.getBuiltinModule('node:path');\n const home = process.env.DSH_HOME || path.join(os.homedir(), '.dsh');\n const raw = JSON.parse(fs.readFileSync(path.join(home, 'agents', 'companion-model.json'), 'utf8'));\n const provider = String((raw && raw.provider) || '').trim();\n const model = String((raw && raw.model) || '').trim();\n if (!provider || !model) return null;\n const reasoningEffort = String((raw && raw.reasoningEffort) || '').trim();\n return { provider, model, ...(reasoningEffort ? { reasoningEffort } : {}) };\n } catch { return null; }\n}\nexport class ModelResolver {"
|
|
158
|
+
},
|
|
159
|
+
{
|
|
160
|
+
"group": "v6",
|
|
161
|
+
"old": " getEffectiveRoute(sessionKey) {\n return this.prefs.getOverride(sessionKey) ?? this.resolveDefault();\n }",
|
|
162
|
+
"new": " getEffectiveRoute(sessionKey) {\n const override = this.prefs.getOverride(sessionKey);\n if (override) return override;\n if (this.config.provider && this.config.model) return { provider: this.config.provider, model: this.config.model };\n // companion-patch:v6 default-model —— 只作用于 QQ 会话的「默认模型(全局)」,不改 DSH 全局默认\n const companion = companionDefaultModel();\n if (companion) return companion;\n return this.resolveDefault();\n }"
|
|
163
|
+
},
|
|
164
|
+
{
|
|
165
|
+
"group": "v6",
|
|
166
|
+
"old": " if (this.config.provider && this.config.model) {\n return { provider: this.config.provider, model: this.config.model };\n }\n return this.resolveDefault();\n }",
|
|
167
|
+
"new": " if (this.config.provider && this.config.model) {\n return { provider: this.config.provider, model: this.config.model };\n }\n // companion-patch:v6 default-model —— 恢复已有 QQ 会话时也用这个默认模型\n const companion = companionDefaultModel();\n if (companion) return companion;\n return this.resolveDefault();\n }"
|
|
112
168
|
}
|
|
113
169
|
]
|
|
114
170
|
}
|
|
@@ -118,5 +174,5 @@
|
|
|
118
174
|
"0.5.4",
|
|
119
175
|
"0.5.5"
|
|
120
176
|
],
|
|
121
|
-
"level":
|
|
122
|
-
}
|
|
177
|
+
"level": 6
|
|
178
|
+
}
|
package/lib/qqbot-patch.mjs
CHANGED
|
@@ -18,7 +18,7 @@ import { join } from 'node:path'
|
|
|
18
18
|
import { spawnSync } from 'node:child_process'
|
|
19
19
|
|
|
20
20
|
const PATCH_FILE = new URL('./qqbot-0.5.3-patches.json', import.meta.url)
|
|
21
|
-
export const PATCH_VERSION =
|
|
21
|
+
export const PATCH_VERSION = 6
|
|
22
22
|
let manifest = null
|
|
23
23
|
function loadManifest() {
|
|
24
24
|
if (!manifest) manifest = JSON.parse(readFileSync(PATCH_FILE, 'utf8'))
|
package/lib/video.mjs
CHANGED
|
@@ -183,7 +183,7 @@ export function createVideoHelper({ home, runProcess, bundledStoryboard = '' })
|
|
|
183
183
|
}
|
|
184
184
|
}
|
|
185
185
|
} catch { /* 没装过 winget 包 */ }
|
|
186
|
-
ffCandidates.push(
|
|
186
|
+
ffCandidates.push(String.raw`C:\ProgramData\chocolatey\bin\ffmpeg.exe`, String.raw`C:\ffmpeg\bin\ffmpeg.exe`)
|
|
187
187
|
}
|
|
188
188
|
for (const c of ffCandidates) { if (existsSync(c)) { addDir(c); break } }
|
|
189
189
|
} catch { /* 补 PATH 失败不影响加载 */ }
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-chat-comprehension",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "DeepSeek Harness 聊天理解/陪伴套件:局部人格 + QQ 联动 + 专属记忆 + B站值班 + 表情包 + 文字转语音,一个入口。",
|
|
@@ -60,4 +60,4 @@
|
|
|
60
60
|
"dependencies": {
|
|
61
61
|
"@deepseek-ai/schemastery": "^3.18.1"
|
|
62
62
|
}
|
|
63
|
-
}
|
|
63
|
+
}
|
|
@@ -79,10 +79,29 @@ export function parsePeerKey(peerKey) {
|
|
|
79
79
|
return { appId: parts[1], scope: parts[2], peerId: parts.slice(3).join(':') }
|
|
80
80
|
}
|
|
81
81
|
|
|
82
|
-
/**
|
|
82
|
+
/** 网关补丁 v4 写的「QQ 聊天 → 会话」表:{ peerKey: { current, sessions[] } }。 */
|
|
83
|
+
function readQqPeerSessions() {
|
|
84
|
+
try {
|
|
85
|
+
const raw = JSON.parse(readFileSync(join(agentsRoot(), 'qq-peers.json'), 'utf8'))
|
|
86
|
+
return raw && typeof raw.peers === 'object' && raw.peers !== null ? raw.peers : {}
|
|
87
|
+
} catch {
|
|
88
|
+
return {}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* 会话 id → peerKey(反查)。
|
|
94
|
+
* 先看 qq-peers.json(网关每确定一个会话都会写,新群第一次说话也在里面),
|
|
95
|
+
* 再看网关自己的 sessionIds(只有切过会话 / 绑定过的聊天才有)。
|
|
96
|
+
*/
|
|
83
97
|
export function peerKeyForSession(sessionId) {
|
|
84
98
|
const id = String(sessionId || '')
|
|
85
99
|
if (id === '') return ''
|
|
100
|
+
for (const [key, row] of Object.entries(readQqPeerSessions())) {
|
|
101
|
+
if (!row || typeof row !== 'object') continue
|
|
102
|
+
if (row.current === id) return key
|
|
103
|
+
if (Array.isArray(row.sessions) && row.sessions.includes(id)) return key
|
|
104
|
+
}
|
|
86
105
|
const sessions = readQqSessions()
|
|
87
106
|
for (const [key, value] of Object.entries(sessions)) {
|
|
88
107
|
if (String(value) === id) return key
|
|
@@ -150,21 +169,27 @@ export function removeChatPersona(peerKey) {
|
|
|
150
169
|
/** 列出所有 QQ 会话(私聊 + 每个群),带人格状态;给设置页用。 */
|
|
151
170
|
export function listChats() {
|
|
152
171
|
const sessions = readQqSessions()
|
|
172
|
+
const gatewayPeers = readQqPeerSessions()
|
|
153
173
|
const registry = readChatRegistry()
|
|
174
|
+
const keys = new Set([...Object.keys(sessions), ...Object.keys(gatewayPeers), ...Object.keys(registry)])
|
|
154
175
|
const out = []
|
|
155
|
-
for (const
|
|
156
|
-
const meta = parsePeerKey(peerKey)
|
|
176
|
+
for (const peerKey of keys) {
|
|
177
|
+
const meta = parsePeerKey(peerKey)
|
|
178
|
+
if (meta === null) continue
|
|
157
179
|
const found = readChatPersona(peerKey)
|
|
158
180
|
const reg = registry[peerKey] || {}
|
|
181
|
+
const gateway = gatewayPeers[peerKey]
|
|
159
182
|
out.push({
|
|
160
183
|
peerKey,
|
|
161
184
|
scope: meta.scope || '',
|
|
162
185
|
peerId: meta.peerId || '',
|
|
163
186
|
appId: meta.appId || '',
|
|
164
|
-
sessionId: String(
|
|
187
|
+
sessionId: String((gateway && gateway.current) || sessions[peerKey] || ''),
|
|
165
188
|
label: reg.label || '',
|
|
166
189
|
hasPersona: found !== null,
|
|
167
190
|
chars: found === null ? 0 : found.chars,
|
|
191
|
+
// 页面要把已保存的人格正文填回输入框;不带 content 的话第二次打开就是一片空白。
|
|
192
|
+
content: found === null ? '' : found.content,
|
|
168
193
|
updatedAt: reg.updatedAt || null,
|
|
169
194
|
file: chatPersonaFile(peerKey),
|
|
170
195
|
})
|
|
@@ -42,15 +42,17 @@ import {
|
|
|
42
42
|
statePath,
|
|
43
43
|
writeTextFile,
|
|
44
44
|
} from './persona.js'
|
|
45
|
-
import { bindQqPeer, parsePeerKey, qqStatus, unbindQqPeer } from './qq.js'
|
|
45
|
+
import { bindQqPeer, parsePeerKey, qqStatus, readBindings, readQqPeers, resetQqPeerSession, setQqModelOverride, syncQqMemoryWithPeers, unbindQqPeer } from './qq.js'
|
|
46
46
|
import {
|
|
47
47
|
composeChatPersona,
|
|
48
48
|
listChats,
|
|
49
49
|
readChatPersona,
|
|
50
50
|
removeChatPersona,
|
|
51
|
+
peerKeyForSession,
|
|
51
52
|
resolveChatPersonaForSession,
|
|
52
53
|
saveChatPersona,
|
|
53
54
|
syncChatRegistry,
|
|
55
|
+
readQqSessions,
|
|
54
56
|
} from './chat-persona.js'
|
|
55
57
|
import { chatModelForSession, globalModel, listChatModels, readChatModels, removeChatModel, saveChatModel } from './chat-models.js'
|
|
56
58
|
import { chatWorkspaceOf, listChatWorkspaces, saveChatWorkspace } from './chat-workspaces.js'
|
|
@@ -378,6 +380,15 @@ export function apply(ctx) {
|
|
|
378
380
|
}
|
|
379
381
|
}
|
|
380
382
|
|
|
383
|
+
// 网关补丁 v4 每确定一个 QQ 会话就更新 qq-peers.json;把它同步进按聊天分组的记忆清单(v1 总表也在这里迁成 v2)
|
|
384
|
+
ctx.effect(() => {
|
|
385
|
+
const tick = () => { try { syncQqMemoryWithPeers() } catch (error) { console.warn('[agent-md] QQ 记忆分组同步失败:' + String((error && error.message) || error)) } }
|
|
386
|
+
tick()
|
|
387
|
+
const timer = setInterval(tick, 5000)
|
|
388
|
+
if (typeof timer.unref === 'function') timer.unref()
|
|
389
|
+
return () => clearInterval(timer)
|
|
390
|
+
}, 'dsh-agent-md: qq memory per chat')
|
|
391
|
+
|
|
381
392
|
// ---- 1. 人格注入 ------------------------------------------------------
|
|
382
393
|
ctx.effect(() => {
|
|
383
394
|
try {
|
|
@@ -430,8 +441,10 @@ export function apply(ctx) {
|
|
|
430
441
|
if (!config.chatModelEnabled || config.enabled === false) return
|
|
431
442
|
const sessionId = String(agent?.id || '')
|
|
432
443
|
if (sessionId === '') return
|
|
433
|
-
//
|
|
434
|
-
|
|
444
|
+
// 会话专属模型优先;普通会话不套用「QQ 默认模型」——
|
|
445
|
+
// 那个默认值只该影响接入 QQ 的对话(用户明确要求:网页里别的对话不要被换掉)。
|
|
446
|
+
const peerKey = peerKeyForSession(sessionId)
|
|
447
|
+
const wanted = chatModelForSession(sessionId) || (peerKey !== '' ? globalModel() : null)
|
|
435
448
|
if (wanted === null) return
|
|
436
449
|
const current = typeof agent.model?.current === 'function' ? agent.model.current() : undefined
|
|
437
450
|
if (current !== undefined && current.provider === wanted.provider && current.model === wanted.model) return
|
|
@@ -776,17 +789,40 @@ export function apply(ctx) {
|
|
|
776
789
|
}
|
|
777
790
|
if (route === '/chats/workspace' && req.method === 'POST') {
|
|
778
791
|
const body = await readBody(req)
|
|
779
|
-
const
|
|
780
|
-
|
|
792
|
+
const peerKey = String(body.peerKey || '')
|
|
793
|
+
const before = chatWorkspaceOf(peerKey)
|
|
794
|
+
const saved = saveChatWorkspace(peerKey, String(body.cwd || ''))
|
|
795
|
+
// 只写文件不够:已经存在的 QQ 会话还是会 resume 回旧目录。
|
|
796
|
+
// 让网关把会话 fork / 重建到新工作区,下一次消息就落在这里。
|
|
797
|
+
// 值没变就不折腾会话(避免同一个工作区被反复重建)。
|
|
798
|
+
const applied = saved.cwd === before ? { ok: true, unchanged: true } : await resetQqPeerSession(ctx, peerKey)
|
|
799
|
+
return sendJson(res, 200, {
|
|
800
|
+
...saved,
|
|
801
|
+
applied,
|
|
802
|
+
chats: listChats().map((c) => ({ ...c, cwd: chatWorkspaceOf(c.peerKey) })),
|
|
803
|
+
})
|
|
781
804
|
}
|
|
782
805
|
if (route === '/chats/model' && req.method === 'POST') {
|
|
783
806
|
const body = await readBody(req)
|
|
784
|
-
const
|
|
785
|
-
|
|
807
|
+
const peerKey = String(body.peerKey || '')
|
|
808
|
+
const provider = String(body.provider || '').trim()
|
|
809
|
+
const model = String(body.model || '').trim()
|
|
810
|
+
// 先确认这个模型 DSH 里真有:选错了别默默存下、到对话时才静默退回默认
|
|
811
|
+
const known = await knownModel(ctx, provider, model)
|
|
812
|
+
if (known === false) throw Object.assign(new Error(`DSH 里没有模型 ${provider}/${model}(provider 没启用或模型名不对)`), { status: 400 })
|
|
813
|
+
const saved = saveChatModel(peerKey, { provider, model, reasoningEffort: body.reasoningEffort })
|
|
814
|
+
// 1) 写进网关自己的 per-peer 覆盖:以后新建 / 恢复这个聊天都会先用这个模型
|
|
815
|
+
let routed = false
|
|
816
|
+
try { routed = setQqModelOverride(peerKey, saved.selection) } catch { routed = false }
|
|
817
|
+
// 2) 这个 QQ 聊天的对话要是正开着,立刻换上,不用等下次重开
|
|
818
|
+
const applied = applyChatModelNow(ctx, peerKey, saved.selection)
|
|
819
|
+
return sendJson(res, 200, { ...saved, routed, applied, models: listChatModels() })
|
|
786
820
|
}
|
|
787
821
|
if (route === '/chats/model/delete' && req.method === 'POST') {
|
|
788
822
|
const body = await readBody(req)
|
|
789
|
-
const
|
|
823
|
+
const peerKey = String(body.peerKey || '')
|
|
824
|
+
const removed = removeChatModel(peerKey)
|
|
825
|
+
try { setQqModelOverride(peerKey, null) } catch { /* 网关没装也不影响删除 */ }
|
|
790
826
|
return sendJson(res, 200, { ...removed, models: listChatModels() })
|
|
791
827
|
}
|
|
792
828
|
if (route === '/qq' && req.method === 'GET') {
|
|
@@ -881,3 +917,39 @@ export function __resetConfigForTest() {
|
|
|
881
917
|
}
|
|
882
918
|
|
|
883
919
|
// global removed 1793149026
|
|
920
|
+
|
|
921
|
+
|
|
922
|
+
/** provider/model 在 DSH 里存在吗?true/false;查不了(老宿主)返回 null,不拦。 */
|
|
923
|
+
async function knownModel(ctx, provider, model) {
|
|
924
|
+
if (!provider || !model) return false
|
|
925
|
+
try {
|
|
926
|
+
const llm = typeof ctx.get === 'function' ? ctx.get('llm') : null
|
|
927
|
+
if (!llm || typeof llm.listModels !== 'function') return null
|
|
928
|
+
const list = await llm.listModels(provider)
|
|
929
|
+
return Array.isArray(list) ? list.some((m) => (m && (m.id || m.model)) === model) : null
|
|
930
|
+
} catch {
|
|
931
|
+
return false
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
/** 给这个 QQ 聊天正在用的对话立刻换模型;返回是否换上了。 */
|
|
936
|
+
function applyChatModelNow(ctx, peerKey, selection) {
|
|
937
|
+
try {
|
|
938
|
+
const row = readQqPeers()[peerKey]
|
|
939
|
+
const bound = readBindings().find((b) => b.peerKey === peerKey)
|
|
940
|
+
// 网关还没写过 qq-peers.json 时,退回绑定记录 / 网关自己的 sessionIds,别让「立刻切换」白点
|
|
941
|
+
const sessionId = (row && row.current) || (bound && bound.sessionId) || readQqSessions()[peerKey] || ''
|
|
942
|
+
let agents = null
|
|
943
|
+
try { agents = typeof ctx.get === 'function' ? ctx.get('agents') : null } catch { agents = null }
|
|
944
|
+
if (!agents) { try { agents = ctx.agents || null } catch { agents = null } }
|
|
945
|
+
const agent = sessionId && agents && typeof agents.get === 'function' ? agents.get(sessionId) : null
|
|
946
|
+
if (!agent || !agent.model || typeof agent.model.select !== 'function') return false
|
|
947
|
+
const pick = selection && selection.provider ? selection : null
|
|
948
|
+
if (!pick) return false
|
|
949
|
+
agent.model.select(pick.reasoningEffort ? { provider: pick.provider, model: pick.model, reasoningEffort: pick.reasoningEffort } : { provider: pick.provider, model: pick.model })
|
|
950
|
+
return true
|
|
951
|
+
} catch (error) {
|
|
952
|
+
console.warn('[agent-md] 立即切换会话模型失败:' + String((error && error.message) || error))
|
|
953
|
+
return false
|
|
954
|
+
}
|
|
955
|
+
}
|