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/lib/index.js CHANGED
@@ -14,6 +14,7 @@
14
14
  */
15
15
  import { spawn } from 'node:child_process'
16
16
  import { ensureQqbotPatched } from './qqbot-patch.mjs'
17
+ import { listModelCapabilities, setModelInput } from './models.mjs'
17
18
  import { expandCards } from './qq-cards.mjs'
18
19
  import { silkAvailable, wavToSilk } from './silk.mjs'
19
20
  import { cosyVoiceTts, customHttpTts, findFfmpeg, fishSpeechTts, gptSovitsTts, openaiLikeTts, probeService, toWav } from './tts-local.mjs'
@@ -31,6 +32,10 @@ export const name = 'companion'
31
32
  export const inject = []
32
33
 
33
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
+ })()
34
39
 
35
40
  function dshHome() {
36
41
  const fromEnv = typeof process.env.DSH_HOME === 'string' ? process.env.DSH_HOME.trim() : ''
@@ -81,6 +86,28 @@ function sendJson(res, status, body) {
81
86
  res.end(text)
82
87
  }
83
88
 
89
+ /**
90
+ * 这些接口能改模型/语音配置、能触发安装脚本、能读聊天记忆,必须只给本页面用。
91
+ * 浏览器发起的跨站请求一定带 Origin(或 Sec-Fetch-Site),这里核对来源;
92
+ * 没有来源头的本地调用(curl、自己的进程)照旧放行。
93
+ */
94
+ export function sameOrigin(req) {
95
+ const headers = (req && req.headers) || {}
96
+ // 本页面自己的请求带这个头;别的网页发不出来(带自定义头的跨站请求要先过 CORS 预检)。
97
+ if (String(headers['x-companion-client'] || '') === '1') return true
98
+ const origin = String(headers.origin || '').trim()
99
+ const host = String(headers.host || '').trim()
100
+ if (origin !== '') {
101
+ let parsed = null
102
+ try { parsed = new URL(origin) } catch { return false }
103
+ if (!/^https?:$/.test(parsed.protocol)) return false
104
+ if (host === '' || parsed.host !== host) return false
105
+ }
106
+ const site = String(headers['sec-fetch-site'] || '').trim().toLowerCase()
107
+ if (site !== '' && site !== 'same-origin' && site !== 'same-site' && site !== 'none') return false
108
+ return true
109
+ }
110
+
84
111
  /** 调用方写错了(参数不对 / 太长)用 400,别跟上游失败的 502 混在一起。 */
85
112
  function badRequest(message) {
86
113
  const error = new Error(message)
@@ -222,7 +249,62 @@ const TTS_DEFAULTS = {
222
249
  pipIndex: '',
223
250
  }
224
251
  // 云端服务要 Key;本地 / 自建服务大多不要
225
- 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
+ }
226
308
  const LOCAL_PROVIDERS = new Set(['qwen3-local', 'qwen3-vllm', 'openai-local', 'gpt-sovits', 'cosyvoice', 'fish-speech', 'custom-http'])
227
309
  const TTS_PRESETS = [
228
310
  {
@@ -252,6 +334,15 @@ const TTS_PRESETS = [
252
334
  language: 'Chinese',
253
335
  note: '用百炼的 Sambert 语音模型(模型名就是音色);要先在百炼控制台把该模型「开启」,免费额度按字符。工作空间可留空,报 workspace 相关错误时再填。',
254
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
+ },
255
346
  {
256
347
  id: 'openai',
257
348
  name: 'OpenAI 兼容(/audio/speech)',
@@ -346,6 +437,9 @@ function readTts() {
346
437
  /** 这套配置能不能真的合成(QQ 网关、页面、体检都用这一个判断)。 */
347
438
  function ttsEnabled(cfg) {
348
439
  if (!cfg || cfg.provider === 'off') return false
440
+ if (cfg.provider === 'deepseek') {
441
+ return String(cfg.model || '').trim() !== '' && sharedDeepseek.key !== ''
442
+ }
349
443
  if (CLOUD_PROVIDERS.has(cfg.provider)) return String(cfg.apiKey || '') !== '' && String(cfg.model || '').trim() !== ''
350
444
  if (cfg.provider === 'qwen3-local') return true
351
445
  if (LOCAL_PROVIDERS.has(cfg.provider)) return /^https?:\/\//i.test(String(cfg.baseUrl || '').trim())
@@ -363,6 +457,7 @@ function writeTts(patch) {
363
457
  const next = { ...readTts(), ...(patch || {}) }
364
458
  const clean = {
365
459
  provider: String(next.provider || 'dashscope'),
460
+ // 已有的 Key 保留(切回别的预设还要用);DeepSeek 预设合成时会强制用 DSH 那份,不会误用这个
366
461
  apiKey: String(next.apiKey || ''),
367
462
  baseUrl: String(next.baseUrl || '').trim(),
368
463
  model: String(next.model || '').trim(),
@@ -425,10 +520,16 @@ function ttsView() {
425
520
  qwenAutoStart: cfg.qwenAutoStart === true,
426
521
  pipIndex: cfg.pipIndex,
427
522
  enabled: ttsEnabled(cfg),
428
- needsKey: CLOUD_PROVIDERS.has(cfg.provider),
523
+ needsKey: CLOUD_PROVIDERS.has(cfg.provider) && cfg.provider !== 'deepseek',
429
524
  local: LOCAL_PROVIDERS.has(cfg.provider),
430
- hasKey: key !== '',
431
- 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)),
432
533
  presets: TTS_PRESETS,
433
534
  qwen3Models: QWEN3_MODELS,
434
535
  qwen3Speakers: QWEN3_SPEAKERS,
@@ -436,6 +537,30 @@ function ttsView() {
436
537
  }
437
538
  }
438
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
+
439
564
  async function dashscopeTts(cfg, text) {
440
565
  const base = String(cfg.baseUrl || TTS_DEFAULTS.baseUrl).replace(/\/+$/, '')
441
566
  const endpoint = base + '/services/aigc/multimodal-generation/generation'
@@ -542,7 +667,7 @@ function assertTtsModel(cfg) {
542
667
  if (/^(paraformer|funasr|qwen3?-asr|qwen-audio-asr|whisper|sensevoice)/i.test(model)) {
543
668
  throw ttsError('「' + model + '」是语音识别(ASR)模型,不能做 TTS;请填 sambert-zhida-v1 这类语音合成模型', 'tts-config')
544
669
  }
545
- if (cfg.provider === 'openai' || LOCAL_PROVIDERS.has(cfg.provider)) return
670
+ if (cfg.provider === 'openai' || cfg.provider === 'deepseek' || LOCAL_PROVIDERS.has(cfg.provider)) return
546
671
  if (cfg.provider === 'dashscope-sambert') {
547
672
  if (!/^sambert/i.test(model)) throw ttsError('Sambert 预设需要 sambert-* 模型;当前是 ' + model, 'tts-config')
548
673
  return
@@ -598,9 +723,15 @@ function assertAudible(seconds, text, model) {
598
723
  }
599
724
 
600
725
  async function synthesize(rawCfg, text) {
601
- 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
+ }
602
732
  if (cfg.provider === 'off') throw ttsError('语音已停用(只发文字)', 'tts-off')
603
733
  if (CLOUD_PROVIDERS.has(cfg.provider)) {
734
+ if (!cfg.apiKey && cfg.provider === 'deepseek') throw ttsError('DSH 里还没有可用的 DeepSeek API Key:到 DSH 设置 → 模型里填一次,这里会自动共用', 'tts-off')
604
735
  if (!cfg.apiKey) throw ttsError('还没有填 API Key(语音未启用,只发文字)', 'tts-off')
605
736
  if (String(cfg.model || '').trim() === '') throw ttsError('还没有填 TTS 模型名(语音未启用,只发文字)', 'tts-off')
606
737
  } else if (!ttsEnabled(cfg)) {
@@ -642,6 +773,13 @@ async function synthesizeRaw(cfg, trimmed) {
642
773
  if (trimmed.length > 4096) throw badRequest('OpenAI 兼容 TTS 一次最多 4096 字(这段 ' + trimmed.length + ' 字)')
643
774
  return await openaiTts(cfg, trimmed)
644
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
+ }
645
783
  if (LOCAL_PROVIDERS.has(cfg.provider)) {
646
784
  if (trimmed.length > 2000) throw badRequest('本地语音一次最多 2000 字(这段 ' + trimmed.length + ' 字)')
647
785
  const meta = { provider: cfg.provider, model: cfg.model || cfg.provider, voice: cfg.voice || '', chars: trimmed.length, contentType: 'audio/wav' }
@@ -769,7 +907,7 @@ async function doctor(ctx) {
769
907
 
770
908
  try {
771
909
  const cap = readJson(CARD_CAPTURE, null)
772
- const lv = Number((qqbotPatchState || {}).level || 0)
910
+ const lv = Number((qp || {}).level || 0)
773
911
  add('qq-cards', 'QQ 分享卡片(小程序 → 视频链接)', lv >= 2,
774
912
  lv >= 2
775
913
  ? ('网关补丁 v' + lv + ' 已打' + (cap ? ' · 最近一张卡片:' + String(cap.at || '').slice(0, 19).replace('T', ' ') + (cap.results && cap.results[0] && cap.results[0].url ? ' · ' + cap.results[0].url : '') : ' · 还没收到过卡片'))
@@ -861,6 +999,52 @@ function writeCompanionModel(next) {
861
999
  return body
862
1000
  }
863
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
+
864
1048
  /* ───────────────────────────── 快照 ───────────────────────────── */
865
1049
 
866
1050
  // 启动时自动识别并给 QQ 网关打补丁;状态给页面/体检用。
@@ -874,19 +1058,90 @@ let voices = null
874
1058
  const CLONE_PREFIX = 'clone:'
875
1059
  const CARD_CAPTURE = join(dshHome(), 'agents', 'qq-last-card.json')
876
1060
 
1061
+ /** 群聊的记忆镜像文件名:和 dsh-world 写的时候用同一套规则(群号后 8 位字母数字)。 */
1062
+ function groupMirrorPath(mainMirror, peerId) {
1063
+ const suffix = String(peerId || '').replace(/[^A-Za-z0-9]/g, '').slice(-8)
1064
+ return String(mainMirror).replace(/\.md$/i, '') + '-group-' + suffix + '.md'
1065
+ }
1066
+
1067
+ /**
1068
+ * 把 qq-memory.json 读成页面要用的形状。
1069
+ *
1070
+ * v2(2026-11-08 起):`{ version: 2, peers: { <peerKey>: { current, sessions } } }`,
1071
+ * 私聊和每个群各一组,各有一份镜像(群是 qq-memory-group-<后8位>.md)。
1072
+ * v1 老文件(`{ current, sessions }`)照旧能显示。
1073
+ * 纯函数(只读文件),便于测试。
1074
+ */
1075
+ export function qqMemoryView(home, { tail = 12000 } = {}) {
1076
+ const agents = join(home, 'agents')
1077
+ const memFile = join(agents, 'qq-memory.json')
1078
+ const mainMirror = join(agents, 'qq-memory.md')
1079
+ const mem = readJson(memFile, {}) || {}
1080
+ const all = []
1081
+ const rows = []
1082
+ const addSessions = (list) => {
1083
+ for (const id of Array.isArray(list) ? list : []) {
1084
+ if (typeof id === 'string' && id !== '' && !all.includes(id)) all.push(id)
1085
+ }
1086
+ }
1087
+ if (mem.peers && typeof mem.peers === 'object') {
1088
+ for (const [peerKey, row] of Object.entries(mem.peers)) {
1089
+ if (!row || typeof row !== 'object') continue
1090
+ const parts = String(peerKey).split(':')
1091
+ const scope = parts[2] === 'group' ? 'group' : 'c2c'
1092
+ const peerId = parts.slice(3).join(':')
1093
+ const sessions = Array.isArray(row.sessions) ? row.sessions.filter((id) => typeof id === 'string' && id !== '') : []
1094
+ addSessions(sessions)
1095
+ const mirrorPath = scope === 'group' ? groupMirrorPath(mainMirror, peerId) : mainMirror
1096
+ rows.push({
1097
+ peerKey, scope, peerId,
1098
+ current: typeof row.current === 'string' ? row.current : '',
1099
+ sessions: sessions.length,
1100
+ mirrorPath,
1101
+ mirrorInfo: fileInfo(mirrorPath),
1102
+ updatedAt: row.updatedAt || null,
1103
+ })
1104
+ }
1105
+ } else {
1106
+ const sessions = Array.isArray(mem.sessions) ? mem.sessions.filter((id) => typeof id === 'string' && id !== '') : []
1107
+ addSessions(sessions)
1108
+ if (sessions.length > 0 || typeof mem.current === 'string') {
1109
+ rows.push({
1110
+ peerKey: 'legacy', scope: 'c2c', peerId: '',
1111
+ current: typeof mem.current === 'string' ? mem.current : '',
1112
+ sessions: sessions.length,
1113
+ mirrorPath: mainMirror,
1114
+ mirrorInfo: fileInfo(mainMirror),
1115
+ updatedAt: null,
1116
+ })
1117
+ }
1118
+ }
1119
+ // 只读一份镜像内容:挑最近更新的那份(私聊那份最常更新时就是它)
1120
+ const shown = rows
1121
+ .filter((r) => r.mirrorInfo.exists)
1122
+ .sort((a, b) => String(b.mirrorInfo.updatedAt || '').localeCompare(String(a.mirrorInfo.updatedAt || '')))[0] || null
1123
+ return {
1124
+ path: memFile,
1125
+ version: mem.peers && typeof mem.peers === 'object' ? 2 : 1,
1126
+ current: (rows.find((r) => r.scope === 'c2c' && r.current) || rows.find((r) => r.current) || {}).current || '',
1127
+ sessions: all,
1128
+ peers: rows,
1129
+ updatedAt: mem.updatedAt || null,
1130
+ mirror: shown ? readTail(shown.mirrorPath, tail) : '',
1131
+ mirrorPath: shown ? shown.mirrorPath : mainMirror,
1132
+ mirrorInfo: shown ? shown.mirrorInfo : fileInfo(mainMirror),
1133
+ }
1134
+ }
1135
+
877
1136
  function snapshot(ctx) {
878
1137
  const home = dshHome()
879
- const agents = join(home, 'agents')
880
1138
  const bili = join(home, 'bili-duty')
881
1139
  const world = join(home, 'worlds', 'default')
882
- const memFile = join(agents, 'qq-memory.json')
883
- const mirrorFile = join(agents, 'qq-memory.md')
884
- const mem = readJson(memFile, {}) || {}
1140
+ const memory = qqMemoryView(home)
885
1141
  const biliCfg = readJson(join(bili, 'config.json'), {}) || {}
886
1142
  const biliState = readJson(join(bili, 'state.json'), {}) || {}
887
1143
  const worldRun = readJson(join(world, 'world.json'), {}) || {}
888
1144
  const log = readTail(join(bili, 'duty.log'), 6000)
889
- const mirror = readTail(mirrorFile, 12000)
890
1145
  const tts = readTts()
891
1146
  const day = new Date().toLocaleDateString('sv-SE')
892
1147
  let qqService = { available: false, online: false, hasTarget: false }
@@ -902,16 +1157,9 @@ function snapshot(ctx) {
902
1157
  } catch { /* 服务还没挂上 */ }
903
1158
  return {
904
1159
  ok: true,
1160
+ version: PLUGIN_VERSION,
905
1161
  home,
906
- memory: {
907
- path: memFile,
908
- current: typeof mem.current === 'string' ? mem.current : '',
909
- sessions: Array.isArray(mem.sessions) ? mem.sessions : [],
910
- updatedAt: mem.updatedAt || null,
911
- mirror,
912
- mirrorPath: mirrorFile,
913
- mirrorInfo: fileInfo(mirrorFile),
914
- },
1162
+ memory,
915
1163
  bili: {
916
1164
  home: bili,
917
1165
  config: biliCfg,
@@ -939,7 +1187,8 @@ function snapshot(ctx) {
939
1187
  provider: tts.provider,
940
1188
  model: tts.model,
941
1189
  voice: tts.voice,
942
- hasKey: String(tts.apiKey || '') !== '',
1190
+ hasKey: String(tts.apiKey || '') !== '' || (tts.provider === 'deepseek' && sharedDeepseek.key !== ''),
1191
+ sharedKeyReady: sharedDeepseek.key !== '',
943
1192
  },
944
1193
  }
945
1194
  }
@@ -947,6 +1196,14 @@ function snapshot(ctx) {
947
1196
  /* ───────────────────────────── 路由 ───────────────────────────── */
948
1197
 
949
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')
950
1207
  // 自动识别已安装的 QQ 网关并打 companion 补丁(补丁被重装覆盖后,下次启动会自己补回来)。
951
1208
  try {
952
1209
  qqbotPatchState = ensureQqbotPatched()
@@ -977,6 +1234,7 @@ export async function apply(ctx) {
977
1234
  qwen3 = null
978
1235
  video = null
979
1236
  voices = null
1237
+ pluginCtx = null
980
1238
  }, 'companion.local-services')
981
1239
  try {
982
1240
  const cfg = readTts()
@@ -1034,6 +1292,7 @@ export async function apply(ctx) {
1034
1292
  path: API,
1035
1293
  handler: async (req, res) => {
1036
1294
  try {
1295
+ if (!sameOrigin(req)) return sendJson(res, 403, { ok: false, error: '跨站请求被拒绝' })
1037
1296
  const url = new URL(req.url || '/', 'http://x')
1038
1297
  const path = url.pathname.slice(API.length) || '/'
1039
1298
  if (req.method === 'GET' && (path === '/' || path === '/state')) {
@@ -1065,6 +1324,17 @@ export async function apply(ctx) {
1065
1324
  } catch { /* 拿不到就返回空表,页面会提示 */ }
1066
1325
  return sendJson(res, 200, out)
1067
1326
  }
1327
+ if (req.method === 'GET' && path === '/models/capabilities') {
1328
+ return sendJson(res, 200, { ok: true, ...(await listModelCapabilities(ctx)) })
1329
+ }
1330
+ if (req.method === 'POST' && path === '/models/input') {
1331
+ const body = await readBody(req)
1332
+ const provider = String(body.provider || '').trim()
1333
+ const model = String(body.model || '').trim()
1334
+ if (!provider || !model) throw badRequest('provider 和 model 都要传')
1335
+ const input = Array.isArray(body.input) ? body.input.map(String) : []
1336
+ return sendJson(res, 200, await setModelInput(ctx, { provider, model, input, reset: body.reset === true }))
1337
+ }
1068
1338
  if (req.method === 'GET' && path === '/model') {
1069
1339
  let live = null
1070
1340
  try {
@@ -1080,23 +1350,32 @@ export async function apply(ctx) {
1080
1350
  if (provider === '' || model === '') return sendJson(res, 400, { ok: false, error: 'provider 和 model 都要选' })
1081
1351
  const reasoningEffort = String(body.reasoningEffort || '').trim()
1082
1352
  const saved = writeCompanionModel({ provider, model, ...(reasoningEffort !== '' ? { reasoningEffort } : {}) })
1083
- // 同步成 DSH 的默认模型:这样 QQ 新会话、B站 值班轮都会用它
1084
- let applied = false
1085
- let applyError = ''
1353
+ // 只写自己的「QQ 默认模型」文件:QQ 网关建的会话会读它(补丁 v6),B站 值班也会读它。
1354
+ // 绝不能再去改 DSH 的全局默认模型 —— 那会把网页里别的对话一起换掉(用户明确要求过)。
1355
+ let applied = null
1086
1356
  try {
1087
- const sel = ctx.get('agentDefaultModel')
1088
- if (sel && typeof sel.saveSelection === 'function') {
1089
- await sel.saveSelection({ provider, model, ...(reasoningEffort !== '' ? { reasoningEffort } : {}) })
1090
- applied = true
1091
- }
1092
- } catch (error) { applyError = String((error && error.message) || error) }
1093
- 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 })
1094
1361
  }
1095
1362
  if (req.method === 'POST' && path === '/model/clear') {
1096
1363
  const file = COMPANION_MODEL_FILE()
1097
1364
  try { if (existsSync(file)) unlinkSync(file) } catch { /* ignore */ }
1098
1365
  return sendJson(res, 200, { ok: true })
1099
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
+ }
1100
1379
  if (req.method === 'GET' && path === '/setup/plan') {
1101
1380
  return sendJson(res, 200, { ok: true, steps: await setupPlan() })
1102
1381
  }
@@ -1193,7 +1472,9 @@ export async function apply(ctx) {
1193
1472
  const file = join(dir, 'qq-' + Date.now() + '-' + Math.random().toString(16).slice(2) + '.' + out.ext)
1194
1473
  writeFileSync(file, out.buffer)
1195
1474
  try {
1196
- await svc.sendVoice(file)
1475
+ // 网关补丁 v4 起 sendVoice 永远 resolve:失败时返回 { ok:false, error },要当真检查
1476
+ const sent = await svc.sendVoice(file)
1477
+ if (sent && sent.ok === false) throw new Error('QQ 语音没发出去:' + (sent.error || '未知原因'))
1197
1478
  } finally {
1198
1479
  try { unlinkSync(file) } catch { /* ignore */ }
1199
1480
  }
@@ -1286,8 +1567,8 @@ export async function apply(ctx) {
1286
1567
  } catch (error) {
1287
1568
  let message = String((error && error.message) || error)
1288
1569
  try { message = redact(message, [readTts().apiKey]) } catch { /* ignore */ }
1289
- // 语音未启用 / 参数不对是调用方的问题(4xx),其余当成上游失败(502)
1290
- const status = error && error.status === 400 ? 400
1570
+ // 4xx 是调用方能自己修的问题(参数、设置冲突、跨站),原样返回;其余上游失败当 502
1571
+ const status = Number.isInteger(error && error.status) && error.status >= 400 && error.status < 500 ? error.status
1291
1572
  : (error && (error.code === 'tts-off' || error.code === 'tts-config')) ? 409
1292
1573
  : (error && error.code === 'tts-empty') ? 422
1293
1574
  : (error && error.code === 'tts-local-down') ? 503 : 502