dsh-chat-comprehension 0.3.2 → 0.3.5

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
@@ -20,6 +20,7 @@ import { cosyVoiceTts, customHttpTts, findFfmpeg, fishSpeechTts, gptSovitsTts, o
20
20
  import { createQwen3Local, QWEN3_MODELS, QWEN3_SPEAKERS } from './qwen3-local.mjs'
21
21
  import { createVideoHelper } from './video.mjs'
22
22
  import { mountVendoredEngines, repairVendoredEngines } from './engines.mjs'
23
+ import { isSetupRunning, runSetup, setupPlan, setupStatus } from './setup.mjs'
23
24
  import { createVoiceStore } from './voices.mjs'
24
25
  import { chmodSync, closeSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, readSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
25
26
  import { homedir } from 'node:os'
@@ -758,6 +759,14 @@ async function doctor(ctx) {
758
759
  mounts.length ? mounts.map((e) => e.pkg + (e.installed ? '(已单独装)' : e.mounted ? '(内置)' : '(挂载失败)')).join(' / ') : '还没挂载',
759
760
  '没单独安装的引擎会从本包 vendor/ 自动挂载;挂载失败看 DSH 日志', '')
760
761
 
762
+ try {
763
+ const plan = await setupPlan()
764
+ const missing = plan.filter((p) => !p.ok && p.required)
765
+ add('setup', '一键安装(依赖总览)', missing.length === 0,
766
+ plan.map((p) => p.label.split('(')[0] + (p.ok ? ' ✓' : (p.required ? ' ✗' : ' ·'))).join(' / '),
767
+ '到「环境」页点「一键安装全部依赖」,按顺序自动装;每步进度会显示在下面', '')
768
+ } catch { /* 拿不到就不显示这一行 */ }
769
+
761
770
  const ttsScript = join(dirname(fileURLToPath(import.meta.url)), 'tts_sambert.py')
762
771
  add('tts-script', 'Sambert 脚本', existsSync(ttsScript), existsSync(ttsScript) ? ttsScript : '缺失', '插件文件不完整,重装插件', '')
763
772
 
@@ -809,6 +818,28 @@ function installYtdlpOnce() {
809
818
  return ytdlpInFlight
810
819
  }
811
820
 
821
+ /* ───────────────────────────── 全局默认模型 ───────────────────────────── */
822
+
823
+ const COMPANION_MODEL_FILE = () => join(dshHome(), 'agents', 'companion-model.json')
824
+
825
+ function readCompanionModel() {
826
+ const cfg = readJson(COMPANION_MODEL_FILE(), {}) || {}
827
+ return {
828
+ provider: String(cfg.provider || '').trim(),
829
+ model: String(cfg.model || '').trim(),
830
+ reasoningEffort: String(cfg.reasoningEffort || '').trim(),
831
+ updatedAt: cfg.updatedAt || null,
832
+ }
833
+ }
834
+
835
+ function writeCompanionModel(next) {
836
+ const file = COMPANION_MODEL_FILE()
837
+ try { mkdirSync(dirname(file), { recursive: true }) } catch { /* ignore */ }
838
+ const body = { ...next, updatedAt: new Date().toISOString() }
839
+ writeFileSync(file, JSON.stringify(body, null, 2), 'utf8')
840
+ return body
841
+ }
842
+
812
843
  /* ───────────────────────────── 快照 ───────────────────────────── */
813
844
 
814
845
  // 启动时自动识别并给 QQ 网关打补丁;状态给页面/体检用。
@@ -875,6 +906,8 @@ function snapshot(ctx) {
875
906
  },
876
907
  qqService,
877
908
  qqbotPatch: qqbotPatchState,
909
+ setup: setupStatus(),
910
+ defaultModel: readCompanionModel(),
878
911
  engines: engineMounts,
879
912
  video: video ? video.view() : null,
880
913
  lastCard: (() => {
@@ -991,6 +1024,64 @@ export async function apply(ctx) {
991
1024
  engineMounts = await repairVendoredEngines(ctx)
992
1025
  return sendJson(res, 200, { ok: engineMounts.every((e) => e.installed || e.mounted), engines: engineMounts })
993
1026
  }
1027
+ if (req.method === 'GET' && path === '/models') {
1028
+ const out = { providers: [], models: {} }
1029
+ try {
1030
+ const llm = ctx.get('llm')
1031
+ const list = llm && typeof llm.listProviders === 'function' ? llm.listProviders() : []
1032
+ out.providers = (Array.isArray(list) ? list : []).map((p) => ({ id: p.id || p.provider || p.name || '', label: p.label || p.name || p.id || '' })).filter((p) => p.id !== '')
1033
+ for (const p of out.providers) {
1034
+ try {
1035
+ const models = llm && typeof llm.listModels === 'function' ? await llm.listModels(p.id) : []
1036
+ out.models[p.id] = (Array.isArray(models) ? models : []).map((m) => ({ id: m.id || m.model || '', label: m.label || m.name || m.id || '' })).filter((m) => m.id !== '')
1037
+ } catch { out.models[p.id] = [] }
1038
+ }
1039
+ } catch { /* 拿不到就返回空表,页面会提示 */ }
1040
+ return sendJson(res, 200, out)
1041
+ }
1042
+ if (req.method === 'GET' && path === '/model') {
1043
+ let live = null
1044
+ try {
1045
+ const sel = ctx.get('agentDefaultModel')
1046
+ live = sel && typeof sel.currentSelection === 'function' ? sel.currentSelection() : null
1047
+ } catch { live = null }
1048
+ return sendJson(res, 200, { ok: true, saved: readCompanionModel(), live })
1049
+ }
1050
+ if (req.method === 'POST' && path === '/model') {
1051
+ const body = await readBody(req)
1052
+ const provider = String(body.provider || '').trim()
1053
+ const model = String(body.model || '').trim()
1054
+ if (provider === '' || model === '') return sendJson(res, 400, { ok: false, error: 'provider 和 model 都要选' })
1055
+ const reasoningEffort = String(body.reasoningEffort || '').trim()
1056
+ const saved = writeCompanionModel({ provider, model, ...(reasoningEffort !== '' ? { reasoningEffort } : {}) })
1057
+ // 同步成 DSH 的默认模型:这样 QQ 新会话、B站 值班轮都会用它
1058
+ let applied = false
1059
+ let applyError = ''
1060
+ try {
1061
+ const sel = ctx.get('agentDefaultModel')
1062
+ if (sel && typeof sel.saveSelection === 'function') {
1063
+ await sel.saveSelection({ provider, model, ...(reasoningEffort !== '' ? { reasoningEffort } : {}) })
1064
+ applied = true
1065
+ }
1066
+ } catch (error) { applyError = String((error && error.message) || error) }
1067
+ return sendJson(res, 200, { ok: true, saved, applied, ...(applyError ? { applyError } : {}) })
1068
+ }
1069
+ if (req.method === 'POST' && path === '/model/clear') {
1070
+ const file = COMPANION_MODEL_FILE()
1071
+ try { if (existsSync(file)) unlinkSync(file) } catch { /* ignore */ }
1072
+ return sendJson(res, 200, { ok: true })
1073
+ }
1074
+ if (req.method === 'GET' && path === '/setup/plan') {
1075
+ return sendJson(res, 200, { ok: true, steps: await setupPlan() })
1076
+ }
1077
+ if (req.method === 'GET' && path === '/setup/status') {
1078
+ return sendJson(res, 200, { ok: true, ...setupStatus() })
1079
+ }
1080
+ if (req.method === 'POST' && path === '/setup/run') {
1081
+ const body = await readBody(req)
1082
+ const only = Array.isArray(body.only) ? body.only.map((x) => String(x)) : []
1083
+ return sendJson(res, 200, runSetup({ only }))
1084
+ }
994
1085
  if (req.method === 'POST' && path === '/bili/setup') {
995
1086
  const biliSetup = ctx.get('biliVenvSetup')
996
1087
  if (!biliSetup || typeof biliSetup.runInstall !== 'function') throw badRequest('B站 内置引擎没有提供安装入口(可能用的是外部已装版本)')
@@ -1248,3 +1339,17 @@ export async function apply(ctx) {
1248
1339
  // vision output schema 1793465763
1249
1340
 
1250
1341
  // remove describe_image 1793466188
1342
+
1343
+ // chat persona/model 1793983325
1344
+
1345
+ // setup+models 1793983640
1346
+
1347
+ // global model ui 1793984780
1348
+
1349
+ // env layout + net 1793986429
1350
+
1351
+ // v034 1793986499
1352
+
1353
+ // ffmpeg probe fix 1793986613
1354
+
1355
+ // workspace 1793989308
package/lib/net.mjs ADDED
@@ -0,0 +1,97 @@
1
+ /**
2
+ * net.mjs —— 安装前的网速探测 + 镜像选择。
3
+ *
4
+ * 目的:装 Python 包 / 下载工具时,别在慢的外网源上干等。
5
+ * 1. 同时对几个候选源发一个小请求,量「首字节时间 + 吞吐」;
6
+ * 2. 按速度排序,选最快的那个;
7
+ * 3. 结果缓存 10 分钟(同一个进程内别反复探)。
8
+ *
9
+ * 只用 node: 内置能力,不额外依赖。
10
+ */
11
+
12
+ const CACHE_MS = 10 * 60_000
13
+ let cache = null
14
+
15
+ /** 测一个 URL:返回 { ok, ms, kbps, error }。只读前 ~64KB,超时就放弃。 */
16
+ export async function probe(url, { timeoutMs = 6000, maxBytes = 64 * 1024 } = {}) {
17
+ const started = Date.now()
18
+ const controller = new AbortController()
19
+ const timer = setTimeout(() => controller.abort(), timeoutMs)
20
+ try {
21
+ const r = await fetch(url, { signal: controller.signal, redirect: 'follow' })
22
+ if (!r.ok) return { ok: false, ms: Date.now() - started, kbps: 0, error: 'HTTP ' + r.status }
23
+ let read = 0
24
+ if (r.body) {
25
+ const reader = r.body.getReader()
26
+ try {
27
+ for (;;) {
28
+ const { done, value } = await reader.read()
29
+ if (done) break
30
+ read += value ? value.length : 0
31
+ if (read >= maxBytes) break
32
+ }
33
+ } finally {
34
+ try { reader.cancel() } catch { /* ignore */ }
35
+ }
36
+ }
37
+ const ms = Date.now() - started
38
+ const kbps = ms > 0 ? Math.round((read / 1024) / (ms / 1000)) : 0
39
+ return { ok: true, ms, kbps }
40
+ } catch (error) {
41
+ return { ok: false, ms: Date.now() - started, kbps: 0, error: String((error && error.message) || error) }
42
+ } finally {
43
+ clearTimeout(timer)
44
+ }
45
+ }
46
+
47
+ /** PyPI 兼容镜像候选(按国内常见程度排列)。 */
48
+ export const PIP_MIRRORS = [
49
+ { id: 'pypi', label: 'PyPI 官方', url: 'https://pypi.org/simple', foreign: true },
50
+ { id: 'tuna', label: '清华', url: 'https://pypi.tuna.tsinghua.edu.cn/simple', foreign: false },
51
+ { id: 'ustc', label: '中科大', url: 'https://mirrors.ustc.edu.cn/pypi/simple', foreign: false },
52
+ { id: 'aliyun', label: '阿里云', url: 'https://mirrors.aliyun.com/pypi/simple', foreign: false },
53
+ ]
54
+
55
+ /**
56
+ * 选出最快的 PyPI 镜像。
57
+ * 规则:国内镜像只要「能通」就优先于外网;外网明显快(>2.5 倍)时才用外网。
58
+ * @returns {{ url: string, label: string, reason: string, results: Array<object> }}
59
+ */
60
+ export async function pickPipMirror({ force = false, log = () => {} } = {}) {
61
+ const now = Date.now()
62
+ if (!force && cache && now - cache.at < CACHE_MS) return cache.value
63
+ log('正在测网速(选一个最快的 PyPI 镜像)…')
64
+ const results = await Promise.all(PIP_MIRRORS.map(async (m) => {
65
+ const r = await probe(m.url + '/', { timeoutMs: 5000 })
66
+ return { ...m, ...r }
67
+ }))
68
+ const dom = results.filter((r) => !r.foreign && r.ok).sort((a, b) => b.kbps - a.kbps)
69
+ const foreign = results.filter((r) => r.foreign && r.ok).sort((a, b) => b.kbps - a.kbps)
70
+ let chosen = null
71
+ let reason = ''
72
+ if (dom.length && foreign.length) {
73
+ if (foreign[0].kbps > dom[0].kbps * 2.5) { chosen = foreign[0]; reason = '外网明显更快(' + foreign[0].kbps + ' KB/s)' }
74
+ else { chosen = dom[0]; reason = '国内镜像优先(' + dom[0].kbps + ' KB/s)' }
75
+ } else if (dom.length) { chosen = dom[0]; reason = '只有国内镜像可用(' + dom[0].kbps + ' KB/s)' }
76
+ else if (foreign.length) { chosen = foreign[0]; reason = '国内镜像不通,用外网(' + foreign[0].kbps + ' KB/s)' }
77
+ else { chosen = { url: PIP_MIRRORS[1].url, label: PIP_MIRRORS[1].label, kbps: 0 }; reason = '都测不出速度,默认清华源' }
78
+ const value = {
79
+ url: chosen.url,
80
+ label: chosen.label,
81
+ reason,
82
+ kbps: chosen.kbps || 0,
83
+ results: results.map((r) => ({ label: r.label, ok: r.ok, ms: r.ms, kbps: r.kbps })),
84
+ }
85
+ log('镜像:' + value.label + '(' + value.reason + ')')
86
+ cache = { at: now, value }
87
+ return value
88
+ }
89
+
90
+ /** 清掉缓存(换网络后想重新测时用)。 */
91
+ export function clearNetCache() { cache = null }
92
+
93
+ /** 一次性网速快照,给页面显示。 */
94
+ export async function speedSnapshot() {
95
+ const r = await Promise.all(PIP_MIRRORS.map(async (m) => ({ label: m.label, ...(await probe(m.url + '/', { timeoutMs: 4000 })) })))
96
+ return r
97
+ }
@@ -71,11 +71,47 @@
71
71
  "new": " // companion-patch:v2 cards —— QQ 小程序卡片(B站 分享等)补上视频链接。\n // 放在访问控制之后:被拦下的消息不会走到这里,也就不会替陌生人去解短链。\n bot.use(async (mCtx, next) => {\n try {\n const cards = ctx && typeof ctx.get === 'function' ? ctx.get('companionCards') : null;\n const msg = mCtx.message;\n if (cards && typeof cards.expand === 'function' && msg) {\n const extra = await cards.expand(msg);\n if (typeof extra === 'string' && extra.trim() !== '') {\n msg.content = (msg.content ? String(msg.content) + '\\n' : '') + extra;\n }\n }\n }\n catch (err) {\n logger.warn(`im-qqbot: companion card expand failed: ${err instanceof Error ? err.message : String(err)}`);\n }\n await next();\n });\n // 4. 群历史缓冲"
72
72
  }
73
73
  ]
74
+ },
75
+ {
76
+ "file": "session/session-manager.js",
77
+ "v1Markers": [
78
+ "companionWorkspace"
79
+ ],
80
+ "steps": [
81
+ {
82
+ "group": "v3",
83
+ "old": "export class SessionManager {",
84
+ "new": "/** dsh-chat-comprehension:按 QQ 会话(peerKey)指定工作区;没配就返回空串 */\nfunction companionWorkspace(peerKey) {\n try {\n if (typeof process.getBuiltinModule !== 'function') return '';\n const fs = process.getBuiltinModule('node:fs');\n const os = process.getBuiltinModule('node:os');\n const path = process.getBuiltinModule('node:path');\n const home = process.env.DSH_HOME || path.join(os.homedir(), '.dsh');\n const map = JSON.parse(fs.readFileSync(path.join(home, 'agents', 'chat-workspaces.json'), 'utf8'));\n const value = typeof peerKey === 'string' ? map[peerKey] : '';\n return typeof value === 'string' ? value : '';\n }\n catch {\n return '';\n }\n}\nexport class SessionManager {"
85
+ },
86
+ {
87
+ "group": "v3",
88
+ "old": [
89
+ " cwd: this.config.cwd || process.cwd(),",
90
+ " cwd: this.workspaceDir(),"
91
+ ],
92
+ "new": [
93
+ " cwd: companionWorkspace(key) || this.config.cwd || process.cwd(),",
94
+ " cwd: companionWorkspace(key) || this.workspaceDir(),"
95
+ ]
96
+ },
97
+ {
98
+ "group": "v3",
99
+ "old": [
100
+ " cwd: this.config.cwd || process.cwd(),",
101
+ " cwd: this.workspaceDir(),"
102
+ ],
103
+ "new": [
104
+ " cwd: companionWorkspace(key) || this.config.cwd || process.cwd(),",
105
+ " cwd: companionWorkspace(key) || this.workspaceDir(),"
106
+ ]
107
+ }
108
+ ]
74
109
  }
75
110
  ],
76
111
  "versions": [
77
112
  "0.5.3",
78
113
  "0.5.4",
79
114
  "0.5.5"
80
- ]
115
+ ],
116
+ "level": 3
81
117
  }
@@ -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 = 2
21
+ export const PATCH_VERSION = 3
22
22
  let manifest = null
23
23
  function loadManifest() {
24
24
  if (!manifest) manifest = JSON.parse(readFileSync(PATCH_FILE, 'utf8'))
@@ -49,15 +49,23 @@ export function applySteps(code, entry) {
49
49
  let next = code
50
50
  const v1Done = Array.isArray(entry.v1Markers) && entry.v1Markers.length > 0 && entry.v1Markers.every((m) => code.includes(m))
51
51
  for (const step of entry.steps) {
52
- const oldText = Array.isArray(step) ? step[0] : step.old
53
- const newText = Array.isArray(step) ? step[1] : step.new
54
- if (typeof oldText !== 'string' || typeof newText !== 'string') return { text: code, changed: false, error: '补丁数据格式不对' }
52
+ // 两种写法:{ old, new } 或 [[oldAlt...], [newAlt...]](不同版本二选一)
53
+ const pair = Array.isArray(step) ? step : null
54
+ const olds = pair ? pair[0] : step.old
55
+ const news = pair ? pair[1] : step.new
56
+ const oldList = Array.isArray(olds) ? olds : [olds]
57
+ const newList = Array.isArray(news) ? news : [news]
58
+ if (oldList.length !== newList.length) return { text: code, changed: false, error: '补丁数据格式不对(old/new 数量不一致)' }
59
+ if (!oldList.every((x) => typeof x === 'string') || !newList.every((x) => typeof x === 'string')) {
60
+ return { text: code, changed: false, error: '补丁数据格式不对' }
61
+ }
55
62
  if (step.group === 'v1' && v1Done) continue
56
- if (next.includes(newText)) continue
57
- if (!next.includes(oldText)) {
58
- return { text: code, changed: false, error: '补丁锚点不匹配(文件可能被改过):' + oldText.slice(0, 60) }
63
+ if (newList.some((n) => next.includes(n))) continue
64
+ const hit = oldList.findIndex((o) => next.includes(o))
65
+ if (hit < 0) {
66
+ return { text: code, changed: false, error: '补丁锚点不匹配(文件可能被改过):' + oldList[0].slice(0, 60) }
59
67
  }
60
- next = next.replace(oldText, newText)
68
+ next = next.replace(oldList[hit], newList[hit])
61
69
  }
62
70
  return { text: next, changed: next !== code, error: '' }
63
71
  }
@@ -109,7 +117,7 @@ function patchOne(pkg) {
109
117
  for (const p of written) { try { writeFileSync(p.file, p.code, 'utf8') } catch { /* 还原失败只能下次再说 */ } }
110
118
  return { found: true, patched: false, changed: false, version, path: bootstrap, level: 0, error: String((error && error.message) || error) }
111
119
  }
112
- return { found: true, patched: true, changed: written.length > 0, version, path: bootstrap, level: PATCH_VERSION }
120
+ return { found: true, patched: true, changed: written.length > 0, version, path: bootstrap, level: (data.level || PATCH_VERSION) }
113
121
  }
114
122
 
115
123
  /** 自动检测并打补丁;返回汇总状态(供页面/体检/日志使用)。 */