dsh-chat-comprehension 0.4.0 → 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 +46 -12
- package/client.js +374 -47
- package/lib/engines.mjs +36 -5
- package/lib/index.js +198 -17
- package/lib/qqbot-0.5.3-patches.json +31 -1
- package/lib/qqbot-patch.mjs +1 -1
- package/lib/video.mjs +1 -1
- package/package.json +1 -1
- package/vendor/dsh-agent-md/lib/chat-persona.js +9 -3
- package/vendor/dsh-agent-md/lib/index.js +26 -8
- package/vendor/dsh-agent-md/lib/qq.js +64 -0
- package/vendor/dsh-bili-scroll/index.js +25 -9
package/lib/engines.mjs
CHANGED
|
@@ -209,8 +209,36 @@ function selfBaseUrl() {
|
|
|
209
209
|
return 'http://127.0.0.1:' + (process.env.PORT || 3080)
|
|
210
210
|
}
|
|
211
211
|
|
|
212
|
-
/**
|
|
213
|
-
|
|
212
|
+
/**
|
|
213
|
+
* 这个引擎是不是作为 profile 的独立行被加载了(老用户的「单独安装」)。
|
|
214
|
+
*
|
|
215
|
+
* 为什么不能只靠 HTTP 探测:新版 DSH 给所有请求都加了登录校验,未登录时任何路径都可能回
|
|
216
|
+
* 401/403;把 401 当成「已加载」会让全新环境里本来该从 vendor 挂载的引擎被跳过。
|
|
217
|
+
*/
|
|
218
|
+
export function loadedFromProfile(ctx, pkg) {
|
|
219
|
+
try {
|
|
220
|
+
const loader = ctx && typeof ctx.get === 'function' ? ctx.get('loader') : null
|
|
221
|
+
const entries = loader && typeof loader.entries === 'function' ? loader.entries() : []
|
|
222
|
+
for (const entry of Array.isArray(entries) ? entries : []) {
|
|
223
|
+
const name = entry && entry.options && entry.options.name
|
|
224
|
+
if (typeof name !== 'string') continue
|
|
225
|
+
if (name !== pkg && !name.startsWith(pkg + '/')) continue
|
|
226
|
+
if (entry.disabled === true) continue
|
|
227
|
+
const fiber = entry.fiber
|
|
228
|
+
if (fiber === null || fiber === undefined) continue
|
|
229
|
+
// Cordis fiber.state:2 = active;老版本没有 state 时退回 runtime 是否就绪
|
|
230
|
+
if (typeof fiber.state === 'number') {
|
|
231
|
+
if (fiber.state !== 2) continue
|
|
232
|
+
} else if (fiber.runtime === null || fiber.runtime === undefined) continue
|
|
233
|
+
return true
|
|
234
|
+
}
|
|
235
|
+
} catch { /* 老宿主没有 loader 服务 */ }
|
|
236
|
+
return false
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** 真正有没有跑起来:先看 profile 行,再看 tools 注册,最后用 HTTP 路由的 JSON 应答兜底。 */
|
|
240
|
+
export async function engineLoaded(ctx, engine) {
|
|
241
|
+
if (loadedFromProfile(ctx, engine.pkg)) return true
|
|
214
242
|
const tools = ctx.get('tools')
|
|
215
243
|
const names = TOOL_NAMES[engine.id]
|
|
216
244
|
if (names && tools && typeof tools.list === 'function') {
|
|
@@ -224,8 +252,11 @@ async function engineLoaded(ctx, engine) {
|
|
|
224
252
|
if (route) {
|
|
225
253
|
try {
|
|
226
254
|
const r = await fetch(selfBaseUrl() + route, { signal: AbortSignal.timeout(3000) })
|
|
227
|
-
// 401/403
|
|
228
|
-
|
|
255
|
+
// 只认「真的返回了 JSON」:401/403(宿主登录校验)和 SPA 的 HTML 兜底都不能算已加载。
|
|
256
|
+
if (r.status !== 200) return false
|
|
257
|
+
if (!/json/i.test(String(r.headers.get('content-type') || ''))) return false
|
|
258
|
+
const body = await r.json()
|
|
259
|
+
return Boolean(body && typeof body === 'object')
|
|
229
260
|
} catch { return false }
|
|
230
261
|
}
|
|
231
262
|
return false
|
|
@@ -265,7 +296,7 @@ export async function mountVendoredEngines(ctx, { force = false } = {}) {
|
|
|
265
296
|
/** 一键修复:先卸掉上次 vendor 挂载,再强制全部重挂(不动 profile 里已单独加载的引擎)。 */
|
|
266
297
|
export async function repairVendoredEngines(ctx) {
|
|
267
298
|
for (const fiber of mounted.values()) {
|
|
268
|
-
try { fiber?.dispose?.() } catch { /* 旧挂载清理失败不影响重挂 */ }
|
|
299
|
+
try { await fiber?.dispose?.() } catch { /* 旧挂载清理失败不影响重挂 */ }
|
|
269
300
|
}
|
|
270
301
|
mounted.clear()
|
|
271
302
|
return mountVendoredEngines(ctx, { force: false })
|
package/lib/index.js
CHANGED
|
@@ -32,6 +32,10 @@ export const name = 'companion'
|
|
|
32
32
|
export const inject = []
|
|
33
33
|
|
|
34
34
|
const API = '/api/companion'
|
|
35
|
+
// 本插件自己的版本号(「关于」页显示;只有读不出来时才留空)
|
|
36
|
+
const PLUGIN_VERSION = (() => {
|
|
37
|
+
try { return String(JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version || '') } catch { return '' }
|
|
38
|
+
})()
|
|
35
39
|
|
|
36
40
|
function dshHome() {
|
|
37
41
|
const fromEnv = typeof process.env.DSH_HOME === 'string' ? process.env.DSH_HOME.trim() : ''
|
|
@@ -245,7 +249,62 @@ const TTS_DEFAULTS = {
|
|
|
245
249
|
pipIndex: '',
|
|
246
250
|
}
|
|
247
251
|
// 云端服务要 Key;本地 / 自建服务大多不要
|
|
248
|
-
const CLOUD_PROVIDERS = new Set(['dashscope', 'dashscope-sambert', 'openai'])
|
|
252
|
+
const CLOUD_PROVIDERS = new Set(['dashscope', 'dashscope-sambert', 'openai', 'deepseek'])
|
|
253
|
+
// DeepSeek 官方 TTS 和 DSH 的大模型共用一个 Key:从宿主 credentials 服务(或环境变量)里读,不复制到插件配置里。
|
|
254
|
+
let pluginCtx = null
|
|
255
|
+
const sharedDeepseek = { key: '', at: 0 }
|
|
256
|
+
const SHARED_KEY_TTL_MS = 60_000
|
|
257
|
+
|
|
258
|
+
/** 兜底:直接从 DSH 的 .credentials.yaml 里找 DEEPSEEK_API_KEY(credentials 服务拿不到时的最后一招)。 */
|
|
259
|
+
function deepseekKeyFromDisk() {
|
|
260
|
+
try {
|
|
261
|
+
const raw = readFileSync(join(dshHome(), '.credentials.yaml'), 'utf8')
|
|
262
|
+
for (const line of raw.split(/\r?\n/)) {
|
|
263
|
+
const m = line.match(/^\s{2}(DEEPSEEK_API_KEY):\s*(\S+)\s*$/)
|
|
264
|
+
if (!m) continue
|
|
265
|
+
const value = m[2].replace(/^['"]|['"]$/g, '')
|
|
266
|
+
if (value !== '') return value
|
|
267
|
+
}
|
|
268
|
+
} catch { /* 没有这个文件或者没权限,就当没配 */ }
|
|
269
|
+
return ''
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** 读 DSH 里已经配好的 DeepSeek Key(credential 引用 / 环境变量 / 凭据文件都会试)。 */
|
|
273
|
+
export async function resolveSharedDeepseekKey(force = false) {
|
|
274
|
+
const now = Date.now()
|
|
275
|
+
if (!force && sharedDeepseek.key !== '' && now - sharedDeepseek.at < SHARED_KEY_TTL_MS) return sharedDeepseek.key
|
|
276
|
+
const refs = ['DEEPSEEK_API_KEY']
|
|
277
|
+
try {
|
|
278
|
+
const llm = pluginCtx && typeof pluginCtx.get === 'function' ? pluginCtx.get('llm') : null
|
|
279
|
+
const list = llm && typeof llm.listConfigurableProviders === 'function' ? llm.listConfigurableProviders() : []
|
|
280
|
+
for (const entry of Array.isArray(list) ? list : []) {
|
|
281
|
+
if (!/deepseek/i.test(String((entry && entry.provider) || ''))) continue
|
|
282
|
+
const envs = entry && entry.nativeAuth && Array.isArray(entry.nativeAuth.env) ? entry.nativeAuth.env : []
|
|
283
|
+
for (const name of envs) if (typeof name === 'string' && name !== '') refs.push(name)
|
|
284
|
+
}
|
|
285
|
+
} catch { /* 老宿主没有 configureable-provider 目录 */ }
|
|
286
|
+
let creds = null
|
|
287
|
+
try { creds = pluginCtx && typeof pluginCtx.get === 'function' ? pluginCtx.get('credentials') : null } catch { creds = null }
|
|
288
|
+
for (const ref of [...new Set(refs)]) {
|
|
289
|
+
try {
|
|
290
|
+
const found = creds && typeof creds.resolve === 'function' ? await creds.resolve(ref) : null
|
|
291
|
+
if (found && typeof found.value === 'string' && found.value !== '') {
|
|
292
|
+
sharedDeepseek.key = found.value
|
|
293
|
+
sharedDeepseek.at = now
|
|
294
|
+
return found.value
|
|
295
|
+
}
|
|
296
|
+
} catch { /* 这个引用没配置就试下一个 */ }
|
|
297
|
+
if (String(process.env[ref] || '') !== '') {
|
|
298
|
+
sharedDeepseek.key = String(process.env[ref])
|
|
299
|
+
sharedDeepseek.at = now
|
|
300
|
+
return sharedDeepseek.key
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
const fromDisk = deepseekKeyFromDisk()
|
|
304
|
+
sharedDeepseek.key = fromDisk
|
|
305
|
+
sharedDeepseek.at = now
|
|
306
|
+
return fromDisk
|
|
307
|
+
}
|
|
249
308
|
const LOCAL_PROVIDERS = new Set(['qwen3-local', 'qwen3-vllm', 'openai-local', 'gpt-sovits', 'cosyvoice', 'fish-speech', 'custom-http'])
|
|
250
309
|
const TTS_PRESETS = [
|
|
251
310
|
{
|
|
@@ -275,6 +334,15 @@ const TTS_PRESETS = [
|
|
|
275
334
|
language: 'Chinese',
|
|
276
335
|
note: '用百炼的 Sambert 语音模型(模型名就是音色);要先在百炼控制台把该模型「开启」,免费额度按字符。工作空间可留空,报 workspace 相关错误时再填。',
|
|
277
336
|
},
|
|
337
|
+
{
|
|
338
|
+
id: 'deepseek',
|
|
339
|
+
name: 'DeepSeek 官方语音(共用 DSH 里的 DeepSeek Key)',
|
|
340
|
+
baseUrl: 'https://api.deepseek.com',
|
|
341
|
+
model: 'deepseek-tts',
|
|
342
|
+
voice: 'stella',
|
|
343
|
+
language: 'Auto',
|
|
344
|
+
note: '不用再填 Key:直接复用 DSH 里已经配好的 DeepSeek API Key(设置 → 模型 里那份)。音色只有 stella(女声)和 tide(男声);语种自动识别(普通话 / 粤语 / 英日韩等)。一次最多 1 万字。',
|
|
345
|
+
},
|
|
278
346
|
{
|
|
279
347
|
id: 'openai',
|
|
280
348
|
name: 'OpenAI 兼容(/audio/speech)',
|
|
@@ -369,6 +437,9 @@ function readTts() {
|
|
|
369
437
|
/** 这套配置能不能真的合成(QQ 网关、页面、体检都用这一个判断)。 */
|
|
370
438
|
function ttsEnabled(cfg) {
|
|
371
439
|
if (!cfg || cfg.provider === 'off') return false
|
|
440
|
+
if (cfg.provider === 'deepseek') {
|
|
441
|
+
return String(cfg.model || '').trim() !== '' && sharedDeepseek.key !== ''
|
|
442
|
+
}
|
|
372
443
|
if (CLOUD_PROVIDERS.has(cfg.provider)) return String(cfg.apiKey || '') !== '' && String(cfg.model || '').trim() !== ''
|
|
373
444
|
if (cfg.provider === 'qwen3-local') return true
|
|
374
445
|
if (LOCAL_PROVIDERS.has(cfg.provider)) return /^https?:\/\//i.test(String(cfg.baseUrl || '').trim())
|
|
@@ -386,6 +457,7 @@ function writeTts(patch) {
|
|
|
386
457
|
const next = { ...readTts(), ...(patch || {}) }
|
|
387
458
|
const clean = {
|
|
388
459
|
provider: String(next.provider || 'dashscope'),
|
|
460
|
+
// 已有的 Key 保留(切回别的预设还要用);DeepSeek 预设合成时会强制用 DSH 那份,不会误用这个
|
|
389
461
|
apiKey: String(next.apiKey || ''),
|
|
390
462
|
baseUrl: String(next.baseUrl || '').trim(),
|
|
391
463
|
model: String(next.model || '').trim(),
|
|
@@ -448,10 +520,16 @@ function ttsView() {
|
|
|
448
520
|
qwenAutoStart: cfg.qwenAutoStart === true,
|
|
449
521
|
pipIndex: cfg.pipIndex,
|
|
450
522
|
enabled: ttsEnabled(cfg),
|
|
451
|
-
needsKey: CLOUD_PROVIDERS.has(cfg.provider),
|
|
523
|
+
needsKey: CLOUD_PROVIDERS.has(cfg.provider) && cfg.provider !== 'deepseek',
|
|
452
524
|
local: LOCAL_PROVIDERS.has(cfg.provider),
|
|
453
|
-
|
|
454
|
-
|
|
525
|
+
// DeepSeek 官方语音:共用 DSH 里那份 Key,不在这里单独存
|
|
526
|
+
sharedKey: cfg.provider === 'deepseek',
|
|
527
|
+
sharedKeyReady: sharedDeepseek.key !== '',
|
|
528
|
+
deepseekKeyReady: sharedDeepseek.key !== '',
|
|
529
|
+
hasKey: cfg.provider === 'deepseek' ? sharedDeepseek.key !== '' : key !== '',
|
|
530
|
+
keyHint: cfg.provider === 'deepseek'
|
|
531
|
+
? (sharedDeepseek.key !== '' ? 'DSH 的 DeepSeek Key' : '')
|
|
532
|
+
: (key === '' ? '' : '••••' + key.slice(-4)),
|
|
455
533
|
presets: TTS_PRESETS,
|
|
456
534
|
qwen3Models: QWEN3_MODELS,
|
|
457
535
|
qwen3Speakers: QWEN3_SPEAKERS,
|
|
@@ -459,6 +537,30 @@ function ttsView() {
|
|
|
459
537
|
}
|
|
460
538
|
}
|
|
461
539
|
|
|
540
|
+
/** DeepSeek 官方整段语音:POST /v1/tools/tts,响应体直接是音频流(默认 WAV)。 */
|
|
541
|
+
export async function deepseekTts(cfg, text) {
|
|
542
|
+
const base = String(cfg.baseUrl || 'https://api.deepseek.com').trim().replace(/\/+$/, '')
|
|
543
|
+
const endpoint = /\/tools\/tts$/i.test(base)
|
|
544
|
+
? base
|
|
545
|
+
: (/\/v1$/i.test(base) ? base + '/tools/tts' : base + '/v1/tools/tts')
|
|
546
|
+
const voice = /^tide$/i.test(String(cfg.voice || '').trim()) ? 'tide' : 'stella'
|
|
547
|
+
const res = await fetch(endpoint, {
|
|
548
|
+
method: 'POST',
|
|
549
|
+
headers: { authorization: 'Bearer ' + String(cfg.apiKey || ''), 'content-type': 'application/json' },
|
|
550
|
+
body: JSON.stringify({ text, voice_id: voice, format: 'wav', filter_markdown: true }),
|
|
551
|
+
signal: AbortSignal.timeout(Math.max(20, Math.min(600, Number(cfg.timeoutSec) || 120)) * 1000),
|
|
552
|
+
})
|
|
553
|
+
const type = String(res.headers.get('content-type') || '')
|
|
554
|
+
if (!res.ok) {
|
|
555
|
+
let detail = ''
|
|
556
|
+
try { detail = (await res.text()).slice(0, 500) } catch { /* ignore */ }
|
|
557
|
+
throw new Error('DeepSeek 语音合成失败(HTTP ' + res.status + ')' + (detail ? ':' + detail : ''))
|
|
558
|
+
}
|
|
559
|
+
const buffer = Buffer.from(await res.arrayBuffer())
|
|
560
|
+
if (buffer.length === 0) throw new Error('DeepSeek 语音合成返回了空音频')
|
|
561
|
+
return { provider: 'deepseek', model: 'deepseek-tts', voice, chars: text.length, contentType: type.startsWith('audio/') ? type : 'audio/wav', buffer }
|
|
562
|
+
}
|
|
563
|
+
|
|
462
564
|
async function dashscopeTts(cfg, text) {
|
|
463
565
|
const base = String(cfg.baseUrl || TTS_DEFAULTS.baseUrl).replace(/\/+$/, '')
|
|
464
566
|
const endpoint = base + '/services/aigc/multimodal-generation/generation'
|
|
@@ -565,7 +667,7 @@ function assertTtsModel(cfg) {
|
|
|
565
667
|
if (/^(paraformer|funasr|qwen3?-asr|qwen-audio-asr|whisper|sensevoice)/i.test(model)) {
|
|
566
668
|
throw ttsError('「' + model + '」是语音识别(ASR)模型,不能做 TTS;请填 sambert-zhida-v1 这类语音合成模型', 'tts-config')
|
|
567
669
|
}
|
|
568
|
-
if (cfg.provider === 'openai' || LOCAL_PROVIDERS.has(cfg.provider)) return
|
|
670
|
+
if (cfg.provider === 'openai' || cfg.provider === 'deepseek' || LOCAL_PROVIDERS.has(cfg.provider)) return
|
|
569
671
|
if (cfg.provider === 'dashscope-sambert') {
|
|
570
672
|
if (!/^sambert/i.test(model)) throw ttsError('Sambert 预设需要 sambert-* 模型;当前是 ' + model, 'tts-config')
|
|
571
673
|
return
|
|
@@ -621,9 +723,15 @@ function assertAudible(seconds, text, model) {
|
|
|
621
723
|
}
|
|
622
724
|
|
|
623
725
|
async function synthesize(rawCfg, text) {
|
|
624
|
-
|
|
726
|
+
let cfg = effectiveCfg(rawCfg)
|
|
727
|
+
if (cfg.provider === 'deepseek') {
|
|
728
|
+
// DeepSeek 官方语音只用 DSH 里那份 Key;配置里可能留着别的服务的 Key,不能误用
|
|
729
|
+
const shared = await resolveSharedDeepseekKey(true)
|
|
730
|
+
cfg = { ...cfg, apiKey: shared }
|
|
731
|
+
}
|
|
625
732
|
if (cfg.provider === 'off') throw ttsError('语音已停用(只发文字)', 'tts-off')
|
|
626
733
|
if (CLOUD_PROVIDERS.has(cfg.provider)) {
|
|
734
|
+
if (!cfg.apiKey && cfg.provider === 'deepseek') throw ttsError('DSH 里还没有可用的 DeepSeek API Key:到 DSH 设置 → 模型里填一次,这里会自动共用', 'tts-off')
|
|
627
735
|
if (!cfg.apiKey) throw ttsError('还没有填 API Key(语音未启用,只发文字)', 'tts-off')
|
|
628
736
|
if (String(cfg.model || '').trim() === '') throw ttsError('还没有填 TTS 模型名(语音未启用,只发文字)', 'tts-off')
|
|
629
737
|
} else if (!ttsEnabled(cfg)) {
|
|
@@ -665,6 +773,13 @@ async function synthesizeRaw(cfg, trimmed) {
|
|
|
665
773
|
if (trimmed.length > 4096) throw badRequest('OpenAI 兼容 TTS 一次最多 4096 字(这段 ' + trimmed.length + ' 字)')
|
|
666
774
|
return await openaiTts(cfg, trimmed)
|
|
667
775
|
}
|
|
776
|
+
if (cfg.provider === 'deepseek') {
|
|
777
|
+
// DeepSeek 按「计费字符」限 1 万:汉字算 2、其它算 1
|
|
778
|
+
let billed = 0
|
|
779
|
+
for (const ch of trimmed) billed += /[\u3000-\u9fff\uf900-\ufaff\uff00-\uffef]/.test(ch) ? 2 : 1
|
|
780
|
+
if (billed > 10000) throw badRequest('DeepSeek 语音一次最多 1 万计费字符(中文按 2 个算,这段约 ' + billed + ')')
|
|
781
|
+
return await deepseekTts(cfg, trimmed)
|
|
782
|
+
}
|
|
668
783
|
if (LOCAL_PROVIDERS.has(cfg.provider)) {
|
|
669
784
|
if (trimmed.length > 2000) throw badRequest('本地语音一次最多 2000 字(这段 ' + trimmed.length + ' 字)')
|
|
670
785
|
const meta = { provider: cfg.provider, model: cfg.model || cfg.provider, voice: cfg.voice || '', chars: trimmed.length, contentType: 'audio/wav' }
|
|
@@ -884,6 +999,52 @@ function writeCompanionModel(next) {
|
|
|
884
999
|
return body
|
|
885
1000
|
}
|
|
886
1001
|
|
|
1002
|
+
/* ── 表情包图库文件夹:批量导入时直接开系统文件管理器 ── */
|
|
1003
|
+
function memeFolderInfo() {
|
|
1004
|
+
const base = String(process.env.DSH_MEME_HOME || '').trim() || homedir()
|
|
1005
|
+
const settings = readJson(join(base, '.dsh', 'dsh-expression.json'), {}) || {}
|
|
1006
|
+
const packsDir = typeof settings.packsDir === 'string' && settings.packsDir.trim() !== ''
|
|
1007
|
+
? settings.packsDir.trim()
|
|
1008
|
+
: join(base, '.dsh', 'meme-packs')
|
|
1009
|
+
const userPack = join(packsDir, 'dsh-meme-user')
|
|
1010
|
+
return {
|
|
1011
|
+
packsDir,
|
|
1012
|
+
userPack,
|
|
1013
|
+
packsDirExists: existsSync(packsDir),
|
|
1014
|
+
userPackExists: existsSync(userPack),
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
/** 用系统文件管理器打开一个目录;没有 xdg-open / open / explorer 时把路径原样带回,页面可以复制。 */
|
|
1019
|
+
function openFolderInOs(dir) {
|
|
1020
|
+
return new Promise((resolve) => {
|
|
1021
|
+
if (!dir) { resolve({ ok: false, error: '没有文件夹路径' }); return }
|
|
1022
|
+
try { mkdirSync(dir, { recursive: true }) } catch (error) {
|
|
1023
|
+
resolve({ ok: false, error: '建不了文件夹:' + String((error && error.message) || error) })
|
|
1024
|
+
return
|
|
1025
|
+
}
|
|
1026
|
+
const cmd = process.platform === 'win32' ? 'explorer.exe' : process.platform === 'darwin' ? 'open' : 'xdg-open'
|
|
1027
|
+
let child = null
|
|
1028
|
+
try {
|
|
1029
|
+
child = spawn(cmd, [dir], { detached: true, stdio: 'ignore', windowsHide: true })
|
|
1030
|
+
} catch (error) {
|
|
1031
|
+
resolve({ ok: false, cmd, error: String((error && error.message) || error) })
|
|
1032
|
+
return
|
|
1033
|
+
}
|
|
1034
|
+
let settled = false
|
|
1035
|
+
const done = (ok, error) => {
|
|
1036
|
+
if (settled) return
|
|
1037
|
+
settled = true
|
|
1038
|
+
try { child.unref() } catch { /* ignore */ }
|
|
1039
|
+
resolve({ ok, cmd, error: error || '' })
|
|
1040
|
+
}
|
|
1041
|
+
child.once('error', (error) => done(false, String((error && error.message) || error)))
|
|
1042
|
+
child.once('spawn', () => done(true, ''))
|
|
1043
|
+
// 有些 Linux 桌面 / explorer 不保证触发 spawn 事件,等一小会儿也当成功
|
|
1044
|
+
setTimeout(() => done(true, ''), 1200)
|
|
1045
|
+
})
|
|
1046
|
+
}
|
|
1047
|
+
|
|
887
1048
|
/* ───────────────────────────── 快照 ───────────────────────────── */
|
|
888
1049
|
|
|
889
1050
|
// 启动时自动识别并给 QQ 网关打补丁;状态给页面/体检用。
|
|
@@ -996,6 +1157,7 @@ function snapshot(ctx) {
|
|
|
996
1157
|
} catch { /* 服务还没挂上 */ }
|
|
997
1158
|
return {
|
|
998
1159
|
ok: true,
|
|
1160
|
+
version: PLUGIN_VERSION,
|
|
999
1161
|
home,
|
|
1000
1162
|
memory,
|
|
1001
1163
|
bili: {
|
|
@@ -1025,7 +1187,8 @@ function snapshot(ctx) {
|
|
|
1025
1187
|
provider: tts.provider,
|
|
1026
1188
|
model: tts.model,
|
|
1027
1189
|
voice: tts.voice,
|
|
1028
|
-
hasKey: String(tts.apiKey || '') !== '',
|
|
1190
|
+
hasKey: String(tts.apiKey || '') !== '' || (tts.provider === 'deepseek' && sharedDeepseek.key !== ''),
|
|
1191
|
+
sharedKeyReady: sharedDeepseek.key !== '',
|
|
1029
1192
|
},
|
|
1030
1193
|
}
|
|
1031
1194
|
}
|
|
@@ -1033,6 +1196,14 @@ function snapshot(ctx) {
|
|
|
1033
1196
|
/* ───────────────────────────── 路由 ───────────────────────────── */
|
|
1034
1197
|
|
|
1035
1198
|
export async function apply(ctx) {
|
|
1199
|
+
pluginCtx = ctx
|
|
1200
|
+
// DeepSeek 官方语音共用 DSH 的大模型 Key:启动时先解析一次,之后每分钟刷新
|
|
1201
|
+
try { await resolveSharedDeepseekKey(true) } catch { /* Key 还没配也不影响插件加载 */ }
|
|
1202
|
+
ctx.effect(() => {
|
|
1203
|
+
const timer = setInterval(() => { void resolveSharedDeepseekKey(true) }, 60_000)
|
|
1204
|
+
if (typeof timer.unref === 'function') timer.unref()
|
|
1205
|
+
return () => clearInterval(timer)
|
|
1206
|
+
}, 'companion.deepseek-key')
|
|
1036
1207
|
// 自动识别已安装的 QQ 网关并打 companion 补丁(补丁被重装覆盖后,下次启动会自己补回来)。
|
|
1037
1208
|
try {
|
|
1038
1209
|
qqbotPatchState = ensureQqbotPatched()
|
|
@@ -1063,6 +1234,7 @@ export async function apply(ctx) {
|
|
|
1063
1234
|
qwen3 = null
|
|
1064
1235
|
video = null
|
|
1065
1236
|
voices = null
|
|
1237
|
+
pluginCtx = null
|
|
1066
1238
|
}, 'companion.local-services')
|
|
1067
1239
|
try {
|
|
1068
1240
|
const cfg = readTts()
|
|
@@ -1178,23 +1350,32 @@ export async function apply(ctx) {
|
|
|
1178
1350
|
if (provider === '' || model === '') return sendJson(res, 400, { ok: false, error: 'provider 和 model 都要选' })
|
|
1179
1351
|
const reasoningEffort = String(body.reasoningEffort || '').trim()
|
|
1180
1352
|
const saved = writeCompanionModel({ provider, model, ...(reasoningEffort !== '' ? { reasoningEffort } : {}) })
|
|
1181
|
-
//
|
|
1182
|
-
|
|
1183
|
-
let
|
|
1353
|
+
// 只写自己的「QQ 默认模型」文件:QQ 网关建的会话会读它(补丁 v6),B站 值班也会读它。
|
|
1354
|
+
// 绝不能再去改 DSH 的全局默认模型 —— 那会把网页里别的对话一起换掉(用户明确要求过)。
|
|
1355
|
+
let applied = null
|
|
1184
1356
|
try {
|
|
1185
|
-
const
|
|
1186
|
-
if (
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
}
|
|
1190
|
-
} catch (error) { applyError = String((error && error.message) || error) }
|
|
1191
|
-
return sendJson(res, 200, { ok: true, saved, applied, ...(applyError ? { applyError } : {}) })
|
|
1357
|
+
const qq = typeof ctx.get === 'function' ? ctx.get('companionQq') : null
|
|
1358
|
+
if (qq && typeof qq.applyDefaultModel === 'function') applied = await qq.applyDefaultModel()
|
|
1359
|
+
} catch { applied = null }
|
|
1360
|
+
return sendJson(res, 200, { ok: true, saved, applied })
|
|
1192
1361
|
}
|
|
1193
1362
|
if (req.method === 'POST' && path === '/model/clear') {
|
|
1194
1363
|
const file = COMPANION_MODEL_FILE()
|
|
1195
1364
|
try { if (existsSync(file)) unlinkSync(file) } catch { /* ignore */ }
|
|
1196
1365
|
return sendJson(res, 200, { ok: true })
|
|
1197
1366
|
}
|
|
1367
|
+
if (req.method === 'GET' && path === '/meme/folders') {
|
|
1368
|
+
return sendJson(res, 200, { ok: true, ...memeFolderInfo() })
|
|
1369
|
+
}
|
|
1370
|
+
if (req.method === 'POST' && path === '/meme/open-folder') {
|
|
1371
|
+
const body = await readBody(req)
|
|
1372
|
+
const which = body.which === 'packs' ? 'packs' : 'user'
|
|
1373
|
+
const before = memeFolderInfo()
|
|
1374
|
+
const dir = which === 'packs' ? before.packsDir : before.userPack
|
|
1375
|
+
const opened = await openFolderInOs(dir)
|
|
1376
|
+
// 打开失败也把路径带回去:页面可以显示 / 复制,让用户自己开
|
|
1377
|
+
return sendJson(res, 200, { ...opened, ...memeFolderInfo(), which, path: dir })
|
|
1378
|
+
}
|
|
1198
1379
|
if (req.method === 'GET' && path === '/setup/plan') {
|
|
1199
1380
|
return sendJson(res, 200, { ok: true, steps: await setupPlan() })
|
|
1200
1381
|
}
|
|
@@ -70,6 +70,16 @@
|
|
|
70
70
|
"group": "v4",
|
|
71
71
|
"old": " const latestReplyTarget = () => {\n let best = null;",
|
|
72
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"
|
|
73
83
|
}
|
|
74
84
|
]
|
|
75
85
|
},
|
|
@@ -137,6 +147,26 @@
|
|
|
137
147
|
"new": " this.modelResolver.setSessionId(key, childId);\n companionRecordPeer(key, childId, record.sessionId); // companion-patch:v4 peers"
|
|
138
148
|
}
|
|
139
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 }"
|
|
168
|
+
}
|
|
169
|
+
]
|
|
140
170
|
}
|
|
141
171
|
],
|
|
142
172
|
"versions": [
|
|
@@ -144,5 +174,5 @@
|
|
|
144
174
|
"0.5.4",
|
|
145
175
|
"0.5.5"
|
|
146
176
|
],
|
|
147
|
-
"level":
|
|
177
|
+
"level": 6
|
|
148
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
|
@@ -169,21 +169,27 @@ export function removeChatPersona(peerKey) {
|
|
|
169
169
|
/** 列出所有 QQ 会话(私聊 + 每个群),带人格状态;给设置页用。 */
|
|
170
170
|
export function listChats() {
|
|
171
171
|
const sessions = readQqSessions()
|
|
172
|
+
const gatewayPeers = readQqPeerSessions()
|
|
172
173
|
const registry = readChatRegistry()
|
|
174
|
+
const keys = new Set([...Object.keys(sessions), ...Object.keys(gatewayPeers), ...Object.keys(registry)])
|
|
173
175
|
const out = []
|
|
174
|
-
for (const
|
|
175
|
-
const meta = parsePeerKey(peerKey)
|
|
176
|
+
for (const peerKey of keys) {
|
|
177
|
+
const meta = parsePeerKey(peerKey)
|
|
178
|
+
if (meta === null) continue
|
|
176
179
|
const found = readChatPersona(peerKey)
|
|
177
180
|
const reg = registry[peerKey] || {}
|
|
181
|
+
const gateway = gatewayPeers[peerKey]
|
|
178
182
|
out.push({
|
|
179
183
|
peerKey,
|
|
180
184
|
scope: meta.scope || '',
|
|
181
185
|
peerId: meta.peerId || '',
|
|
182
186
|
appId: meta.appId || '',
|
|
183
|
-
sessionId: String(
|
|
187
|
+
sessionId: String((gateway && gateway.current) || sessions[peerKey] || ''),
|
|
184
188
|
label: reg.label || '',
|
|
185
189
|
hasPersona: found !== null,
|
|
186
190
|
chars: found === null ? 0 : found.chars,
|
|
191
|
+
// 页面要把已保存的人格正文填回输入框;不带 content 的话第二次打开就是一片空白。
|
|
192
|
+
content: found === null ? '' : found.content,
|
|
187
193
|
updatedAt: reg.updatedAt || null,
|
|
188
194
|
file: chatPersonaFile(peerKey),
|
|
189
195
|
})
|
|
@@ -42,12 +42,13 @@ import {
|
|
|
42
42
|
statePath,
|
|
43
43
|
writeTextFile,
|
|
44
44
|
} from './persona.js'
|
|
45
|
-
import { bindQqPeer, parsePeerKey, qqStatus, readBindings, readQqPeers, syncQqMemoryWithPeers, 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,
|
|
@@ -440,8 +441,10 @@ export function apply(ctx) {
|
|
|
440
441
|
if (!config.chatModelEnabled || config.enabled === false) return
|
|
441
442
|
const sessionId = String(agent?.id || '')
|
|
442
443
|
if (sessionId === '') return
|
|
443
|
-
//
|
|
444
|
-
|
|
444
|
+
// 会话专属模型优先;普通会话不套用「QQ 默认模型」——
|
|
445
|
+
// 那个默认值只该影响接入 QQ 的对话(用户明确要求:网页里别的对话不要被换掉)。
|
|
446
|
+
const peerKey = peerKeyForSession(sessionId)
|
|
447
|
+
const wanted = chatModelForSession(sessionId) || (peerKey !== '' ? globalModel() : null)
|
|
445
448
|
if (wanted === null) return
|
|
446
449
|
const current = typeof agent.model?.current === 'function' ? agent.model.current() : undefined
|
|
447
450
|
if (current !== undefined && current.provider === wanted.provider && current.model === wanted.model) return
|
|
@@ -786,8 +789,18 @@ export function apply(ctx) {
|
|
|
786
789
|
}
|
|
787
790
|
if (route === '/chats/workspace' && req.method === 'POST') {
|
|
788
791
|
const body = await readBody(req)
|
|
789
|
-
const
|
|
790
|
-
|
|
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
|
+
})
|
|
791
804
|
}
|
|
792
805
|
if (route === '/chats/model' && req.method === 'POST') {
|
|
793
806
|
const body = await readBody(req)
|
|
@@ -798,13 +811,18 @@ export function apply(ctx) {
|
|
|
798
811
|
const known = await knownModel(ctx, provider, model)
|
|
799
812
|
if (known === false) throw Object.assign(new Error(`DSH 里没有模型 ${provider}/${model}(provider 没启用或模型名不对)`), { status: 400 })
|
|
800
813
|
const saved = saveChatModel(peerKey, { provider, model, reasoningEffort: body.reasoningEffort })
|
|
801
|
-
//
|
|
814
|
+
// 1) 写进网关自己的 per-peer 覆盖:以后新建 / 恢复这个聊天都会先用这个模型
|
|
815
|
+
let routed = false
|
|
816
|
+
try { routed = setQqModelOverride(peerKey, saved.selection) } catch { routed = false }
|
|
817
|
+
// 2) 这个 QQ 聊天的对话要是正开着,立刻换上,不用等下次重开
|
|
802
818
|
const applied = applyChatModelNow(ctx, peerKey, saved.selection)
|
|
803
|
-
return sendJson(res, 200, { ...saved, applied, models: listChatModels() })
|
|
819
|
+
return sendJson(res, 200, { ...saved, routed, applied, models: listChatModels() })
|
|
804
820
|
}
|
|
805
821
|
if (route === '/chats/model/delete' && req.method === 'POST') {
|
|
806
822
|
const body = await readBody(req)
|
|
807
|
-
const
|
|
823
|
+
const peerKey = String(body.peerKey || '')
|
|
824
|
+
const removed = removeChatModel(peerKey)
|
|
825
|
+
try { setQqModelOverride(peerKey, null) } catch { /* 网关没装也不影响删除 */ }
|
|
808
826
|
return sendJson(res, 200, { ...removed, models: listChatModels() })
|
|
809
827
|
}
|
|
810
828
|
if (route === '/qq' && req.method === 'GET') {
|