dsh-chat-comprehension 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/NOTICE.md +4 -3
  2. package/README.md +62 -15
  3. package/client.js +400 -52
  4. package/lib/engines.mjs +36 -5
  5. package/lib/index.js +210 -20
  6. package/lib/qqbot-0.5.3-patches.json +31 -1
  7. package/lib/qqbot-patch.mjs +1 -1
  8. package/lib/video.mjs +45 -2
  9. package/package.json +6 -6
  10. package/vendor/dsh-agent-md/lib/chat-persona.js +9 -3
  11. package/vendor/dsh-agent-md/lib/index.js +72 -18
  12. package/vendor/dsh-agent-md/lib/qq.js +64 -0
  13. package/vendor/dsh-agent-md/package.json +1 -1
  14. package/vendor/dsh-bili-scroll/index.js +39 -10
  15. package/vendor/dsh-meme/index.js +3 -1
  16. package/vendor/dsh-video-storyboard/LICENSE-workbuddy.txt +21 -0
  17. package/vendor/dsh-video-storyboard/NOTICE +7 -0
  18. package/vendor/dsh-video-storyboard/NOTICE-workbuddy.md +18 -0
  19. package/vendor/dsh-video-storyboard/dsh.plugin.json +1 -1
  20. package/vendor/dsh-video-storyboard/package.json +1 -1
  21. package/vendor/dsh-video-storyboard/src/sniff.mjs +545 -0
  22. package/vendor/dsh-video-storyboard/src/storyboard/direct-url.js +2 -2
  23. package/vendor/dsh-video-storyboard/src/storyboard/fetch.js +3 -3
  24. package/vendor/dsh-video-storyboard/src/storyboard/pipeline.js +1 -1
  25. package/vendor/dsh-video-storyboard/src/storyboard/source.js +409 -0
  26. package/vendor/dsh-video-storyboard/src/storyboard/tool-spec.js +5 -3
  27. package/vendor/dsh-video-storyboard/src/storyboard/url.js +105 -17
  28. package/vendor/dsh-video-storyboard/src/tools/locate.js +1 -1
  29. package/vendor/dsh-video-storyboard/src/tools/probe.js +4 -6
  30. package/vendor/dsh-video-storyboard/src/tools/zoom.js +1 -1
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
- /** 真正有没有跑起来:优先看 tools 注册,再看引擎自己的 HTTP 路由。 */
213
- async function engineLoaded(ctx, engine) {
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 也说明引擎路由在;404 才是没加载
228
- return r.status !== 404
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
- hasKey: key !== '',
454
- keyHint: key === '' ? '' : '••••' + key.slice(-4),
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
- const cfg = effectiveCfg(rawCfg)
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' }
@@ -803,12 +918,14 @@ async function doctor(ctx) {
803
918
  try {
804
919
  const sb = video ? video.storyboard() : { installed: false }
805
920
  const yt = video ? await video.ytdlp() : { found: false }
806
- add('video-tools', '视频分镜工具链(ffmpeg / yt-dlp)',
921
+ const vv = video ? video.view() : null
922
+ add('video-tools', '看视频工具链(ffmpeg / yt-dlp / 嗅探浏览器)',
807
923
  Boolean(sb.installed && yt.found),
808
924
  (sb.installed ? '分镜 ' + (sb.version || '?') + (sb.bundled ? '(内置)' : '') : '分镜没装')
809
925
  + ' · yt-dlp ' + (yt.found ? yt.bin : '没找到')
810
- + ' · ffmpeg ' + (findFfmpeg(dshHome()) || '没找到'),
811
- 'QQ 分享的视频要这两个才能看;点「一键安装全部依赖」会一起装好', '')
926
+ + ' · ffmpeg ' + (findFfmpeg(dshHome()) || '没找到')
927
+ + ' · 嗅探 ' + (vv && vv.browser ? '可用' : '无浏览器(仍可用 yt-dlp)'),
928
+ '看视频要 ffmpeg / yt-dlp;网页嗅探额外需要 Edge/Chrome。点「一键安装全部依赖」会装前两个', '')
812
929
  } catch { /* 拿不到就不显示 */ }
813
930
 
814
931
  const ttsScript = join(dirname(fileURLToPath(import.meta.url)), 'tts_sambert.py')
@@ -884,6 +1001,52 @@ function writeCompanionModel(next) {
884
1001
  return body
885
1002
  }
886
1003
 
1004
+ /* ── 表情包图库文件夹:批量导入时直接开系统文件管理器 ── */
1005
+ function memeFolderInfo() {
1006
+ const base = String(process.env.DSH_MEME_HOME || '').trim() || homedir()
1007
+ const settings = readJson(join(base, '.dsh', 'dsh-expression.json'), {}) || {}
1008
+ const packsDir = typeof settings.packsDir === 'string' && settings.packsDir.trim() !== ''
1009
+ ? settings.packsDir.trim()
1010
+ : join(base, '.dsh', 'meme-packs')
1011
+ const userPack = join(packsDir, 'dsh-meme-user')
1012
+ return {
1013
+ packsDir,
1014
+ userPack,
1015
+ packsDirExists: existsSync(packsDir),
1016
+ userPackExists: existsSync(userPack),
1017
+ }
1018
+ }
1019
+
1020
+ /** 用系统文件管理器打开一个目录;没有 xdg-open / open / explorer 时把路径原样带回,页面可以复制。 */
1021
+ function openFolderInOs(dir) {
1022
+ return new Promise((resolve) => {
1023
+ if (!dir) { resolve({ ok: false, error: '没有文件夹路径' }); return }
1024
+ try { mkdirSync(dir, { recursive: true }) } catch (error) {
1025
+ resolve({ ok: false, error: '建不了文件夹:' + String((error && error.message) || error) })
1026
+ return
1027
+ }
1028
+ const cmd = process.platform === 'win32' ? 'explorer.exe' : process.platform === 'darwin' ? 'open' : 'xdg-open'
1029
+ let child = null
1030
+ try {
1031
+ child = spawn(cmd, [dir], { detached: true, stdio: 'ignore', windowsHide: true })
1032
+ } catch (error) {
1033
+ resolve({ ok: false, cmd, error: String((error && error.message) || error) })
1034
+ return
1035
+ }
1036
+ let settled = false
1037
+ const done = (ok, error) => {
1038
+ if (settled) return
1039
+ settled = true
1040
+ try { child.unref() } catch { /* ignore */ }
1041
+ resolve({ ok, cmd, error: error || '' })
1042
+ }
1043
+ child.once('error', (error) => done(false, String((error && error.message) || error)))
1044
+ child.once('spawn', () => done(true, ''))
1045
+ // 有些 Linux 桌面 / explorer 不保证触发 spawn 事件,等一小会儿也当成功
1046
+ setTimeout(() => done(true, ''), 1200)
1047
+ })
1048
+ }
1049
+
887
1050
  /* ───────────────────────────── 快照 ───────────────────────────── */
888
1051
 
889
1052
  // 启动时自动识别并给 QQ 网关打补丁;状态给页面/体检用。
@@ -996,6 +1159,7 @@ function snapshot(ctx) {
996
1159
  } catch { /* 服务还没挂上 */ }
997
1160
  return {
998
1161
  ok: true,
1162
+ version: PLUGIN_VERSION,
999
1163
  home,
1000
1164
  memory,
1001
1165
  bili: {
@@ -1025,7 +1189,8 @@ function snapshot(ctx) {
1025
1189
  provider: tts.provider,
1026
1190
  model: tts.model,
1027
1191
  voice: tts.voice,
1028
- hasKey: String(tts.apiKey || '') !== '',
1192
+ hasKey: String(tts.apiKey || '') !== '' || (tts.provider === 'deepseek' && sharedDeepseek.key !== ''),
1193
+ sharedKeyReady: sharedDeepseek.key !== '',
1029
1194
  },
1030
1195
  }
1031
1196
  }
@@ -1033,6 +1198,14 @@ function snapshot(ctx) {
1033
1198
  /* ───────────────────────────── 路由 ───────────────────────────── */
1034
1199
 
1035
1200
  export async function apply(ctx) {
1201
+ pluginCtx = ctx
1202
+ // DeepSeek 官方语音共用 DSH 的大模型 Key:启动时先解析一次,之后每分钟刷新
1203
+ try { await resolveSharedDeepseekKey(true) } catch { /* Key 还没配也不影响插件加载 */ }
1204
+ ctx.effect(() => {
1205
+ const timer = setInterval(() => { void resolveSharedDeepseekKey(true) }, 60_000)
1206
+ if (typeof timer.unref === 'function') timer.unref()
1207
+ return () => clearInterval(timer)
1208
+ }, 'companion.deepseek-key')
1036
1209
  // 自动识别已安装的 QQ 网关并打 companion 补丁(补丁被重装覆盖后,下次启动会自己补回来)。
1037
1210
  try {
1038
1211
  qqbotPatchState = ensureQqbotPatched()
@@ -1063,6 +1236,7 @@ export async function apply(ctx) {
1063
1236
  qwen3 = null
1064
1237
  video = null
1065
1238
  voices = null
1239
+ pluginCtx = null
1066
1240
  }, 'companion.local-services')
1067
1241
  try {
1068
1242
  const cfg = readTts()
@@ -1178,23 +1352,32 @@ export async function apply(ctx) {
1178
1352
  if (provider === '' || model === '') return sendJson(res, 400, { ok: false, error: 'provider 和 model 都要选' })
1179
1353
  const reasoningEffort = String(body.reasoningEffort || '').trim()
1180
1354
  const saved = writeCompanionModel({ provider, model, ...(reasoningEffort !== '' ? { reasoningEffort } : {}) })
1181
- // 同步成 DSH 的默认模型:这样 QQ 新会话、B站 值班轮都会用它
1182
- let applied = false
1183
- let applyError = ''
1355
+ // 只写自己的「QQ 默认模型」文件:QQ 网关建的会话会读它(补丁 v6),B站 值班也会读它。
1356
+ // 绝不能再去改 DSH 的全局默认模型 —— 那会把网页里别的对话一起换掉(用户明确要求过)。
1357
+ let applied = null
1184
1358
  try {
1185
- const sel = ctx.get('agentDefaultModel')
1186
- if (sel && typeof sel.saveSelection === 'function') {
1187
- await sel.saveSelection({ provider, model, ...(reasoningEffort !== '' ? { reasoningEffort } : {}) })
1188
- applied = true
1189
- }
1190
- } catch (error) { applyError = String((error && error.message) || error) }
1191
- return sendJson(res, 200, { ok: true, saved, applied, ...(applyError ? { applyError } : {}) })
1359
+ const qq = typeof ctx.get === 'function' ? ctx.get('companionQq') : null
1360
+ if (qq && typeof qq.applyDefaultModel === 'function') applied = await qq.applyDefaultModel()
1361
+ } catch { applied = null }
1362
+ return sendJson(res, 200, { ok: true, saved, applied })
1192
1363
  }
1193
1364
  if (req.method === 'POST' && path === '/model/clear') {
1194
1365
  const file = COMPANION_MODEL_FILE()
1195
1366
  try { if (existsSync(file)) unlinkSync(file) } catch { /* ignore */ }
1196
1367
  return sendJson(res, 200, { ok: true })
1197
1368
  }
1369
+ if (req.method === 'GET' && path === '/meme/folders') {
1370
+ return sendJson(res, 200, { ok: true, ...memeFolderInfo() })
1371
+ }
1372
+ if (req.method === 'POST' && path === '/meme/open-folder') {
1373
+ const body = await readBody(req)
1374
+ const which = body.which === 'packs' ? 'packs' : 'user'
1375
+ const before = memeFolderInfo()
1376
+ const dir = which === 'packs' ? before.packsDir : before.userPack
1377
+ const opened = await openFolderInOs(dir)
1378
+ // 打开失败也把路径带回去:页面可以显示 / 复制,让用户自己开
1379
+ return sendJson(res, 200, { ...opened, ...memeFolderInfo(), which, path: dir })
1380
+ }
1198
1381
  if (req.method === 'GET' && path === '/setup/plan') {
1199
1382
  return sendJson(res, 200, { ok: true, steps: await setupPlan() })
1200
1383
  }
@@ -1382,6 +1565,13 @@ export async function apply(ctx) {
1382
1565
  const r = video.setBiliLogin(body.on)
1383
1566
  return sendJson(res, r.ok ? 200 : 409, { ...r, ...video.view() })
1384
1567
  }
1568
+ if (req.method === 'POST' && path === '/video/sniff') {
1569
+ const body = await readBody(req)
1570
+ if (typeof body.on !== 'boolean') throw badRequest('要传 on: true / false')
1571
+ if (!video) throw new Error('插件还没初始化完')
1572
+ const r = video.setSniff(body.on)
1573
+ return sendJson(res, 200, { ...r, ...video.view() })
1574
+ }
1385
1575
  return sendJson(res, 404, { error: `unknown ${req.method} ${path}` })
1386
1576
  } catch (error) {
1387
1577
  let message = String((error && error.message) || error)
@@ -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": 5
177
+ "level": 6
148
178
  }
@@ -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 = 5
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
@@ -95,6 +95,46 @@ export function createVideoHelper({ home, runProcess, bundledStoryboard = '' })
95
95
  }
96
96
  }
97
97
 
98
+ /** 找嗅探用的 Edge / Chrome:先看 video.json / 环境变量,再按平台常见安装位置。 */
99
+ function findBrowser() {
100
+ const cfg = readJson(videoJson, {}) || {}
101
+ const explicit = process.env.DSH_VIDEO_BROWSER_PATH || process.env.VIDEO_BROWSER_PATH || cfg.browserPath || ''
102
+ if (explicit && existsSync(explicit)) return explicit
103
+ const pf = process.env.ProgramFiles || ''
104
+ const pfx86 = process.env['PROGRAMFILES(X86)'] || ''
105
+ const local = process.env.LOCALAPPDATA || ''
106
+ const candidates = process.platform === 'win32'
107
+ ? [
108
+ pf && join(pf, 'Microsoft', 'Edge', 'Application', 'msedge.exe'),
109
+ pfx86 && join(pfx86, 'Microsoft', 'Edge', 'Application', 'msedge.exe'),
110
+ local && join(local, 'Microsoft', 'Edge', 'Application', 'msedge.exe'),
111
+ pf && join(pf, 'Google', 'Chrome', 'Application', 'chrome.exe'),
112
+ local && join(local, 'Google', 'Chrome', 'Application', 'chrome.exe'),
113
+ ]
114
+ : process.platform === 'darwin'
115
+ ? ['/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge']
116
+ : ['/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser', '/usr/bin/microsoft-edge']
117
+ return candidates.filter(Boolean).find((p) => existsSync(p)) || ''
118
+ }
119
+
120
+ /** 把嗅探配置同步给内置分镜引擎(它按进程环境变量读;调用时再读,所以改完立即生效)。 */
121
+ function applySniffEnv() {
122
+ const cfg = readJson(videoJson, {}) || {}
123
+ process.env.DSH_VIDEO_SNIFF = cfg.sniff === false ? 'false' : 'true'
124
+ const browser = findBrowser()
125
+ if (browser) process.env.DSH_VIDEO_BROWSER_PATH = browser
126
+ else delete process.env.DSH_VIDEO_BROWSER_PATH
127
+ }
128
+
129
+ /** 网页嗅探开关:yt-dlp 认不出的页面交给无头 Edge/Chrome 找真实媒体地址。 */
130
+ function setSniff(on) {
131
+ const cfg = readJson(videoJson, {}) || {}
132
+ cfg.sniff = on !== false
133
+ writeFileSync(videoJson, JSON.stringify(cfg, null, 2), 'utf8')
134
+ applySniffEnv()
135
+ return { ok: true, sniff: cfg.sniff, browser: findBrowser() }
136
+ }
137
+
98
138
  function settings() {
99
139
  const s = readJson(settingsFile, {}) || {}
100
140
  return { useBiliLogin: s.useBiliLogin === true }
@@ -183,7 +223,7 @@ export function createVideoHelper({ home, runProcess, bundledStoryboard = '' })
183
223
  }
184
224
  }
185
225
  } catch { /* 没装过 winget 包 */ }
186
- ffCandidates.push('C:\ProgramData\chocolatey\bin\ffmpeg.exe', 'C:\ffmpeg\bin\ffmpeg.exe')
226
+ ffCandidates.push(String.raw`C:\ProgramData\chocolatey\bin\ffmpeg.exe`, String.raw`C:\ffmpeg\bin\ffmpeg.exe`)
187
227
  }
188
228
  for (const c of ffCandidates) { if (existsSync(c)) { addDir(c); break } }
189
229
  } catch { /* 补 PATH 失败不影响加载 */ }
@@ -198,6 +238,7 @@ export function createVideoHelper({ home, runProcess, bundledStoryboard = '' })
198
238
  /** 插件启动时:开着就刷新一次 cookies(专用号可能重新登录过);关着就确保没有残留。 */
199
239
  function sync() {
200
240
  try {
241
+ applySniffEnv()
201
242
  if (settings().useBiliLogin) { if (writeCookies()) pointVideoJson(true) } else if (existsSync(cookieFile)) setBiliLogin(false)
202
243
  } catch { /* 不影响插件加载 */ }
203
244
  }
@@ -210,9 +251,11 @@ export function createVideoHelper({ home, runProcess, bundledStoryboard = '' })
210
251
  biliLoggedIn: existsSync(credFile),
211
252
  cookiesConfigured: Boolean(cfg.cookies),
212
253
  cookiesOurs: cfg.cookies === cookieFile,
254
+ sniff: cfg.sniff !== false,
255
+ browser: findBrowser(),
213
256
  install: { state: install.state, step: install.step },
214
257
  }
215
258
  }
216
259
 
217
- return { storyboard, ytdlp, installYtdlp, setBiliLogin, sync, view, cookieFile, ensureToolPath }
260
+ return { storyboard, ytdlp, installYtdlp, setBiliLogin, setSniff, sync, view, cookieFile, ensureToolPath }
218
261
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-chat-comprehension",
3
- "version": "0.4.0",
3
+ "version": "0.5.1",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "DeepSeek Harness 聊天理解/陪伴套件:局部人格 + QQ 联动 + 专属记忆 + B站值班 + 表情包 + 文字转语音,一个入口。",
@@ -33,7 +33,7 @@
33
33
  ],
34
34
  "peerDependencies": {
35
35
  "@deepseek-ai/cordis": "^4.0.1",
36
- "react": "^18.3.1",
36
+ "react": "^18.3.1 || ^19.0.0",
37
37
  "@tencent-connect/dsh-qqbot": "*"
38
38
  },
39
39
  "dsh": {
@@ -42,10 +42,7 @@
42
42
  },
43
43
  "client": {
44
44
  "platform": "web",
45
- "inject": [
46
- "@deepseek-ai/dsh-client-runtime",
47
- "@deepseek-ai/dsh-client-ui-settings"
48
- ]
45
+ "inject": []
49
46
  }
50
47
  },
51
48
  "license": "MIT",
@@ -59,5 +56,8 @@
59
56
  },
60
57
  "dependencies": {
61
58
  "@deepseek-ai/schemastery": "^3.18.1"
59
+ },
60
+ "engines": {
61
+ "dsh": "^0.2.2-alpha.5 || ^0.2.3-alpha.1"
62
62
  }
63
63
  }
@@ -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 [peerKey, sessionId] of Object.entries(sessions)) {
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(sessionId || ''),
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
  })