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/README.md +96 -114
- package/client.js +399 -23
- package/lib/index.js +105 -0
- package/lib/net.mjs +97 -0
- package/lib/qqbot-0.5.3-patches.json +37 -1
- package/lib/qqbot-patch.mjs +17 -9
- package/lib/setup.mjs +431 -0
- package/package.json +1 -1
- package/vendor/dsh-agent-md/lib/chat-models.js +116 -0
- package/vendor/dsh-agent-md/lib/chat-persona.js +207 -0
- package/vendor/dsh-agent-md/lib/chat-workspaces.js +81 -0
- package/vendor/dsh-agent-md/lib/index.js +108 -0
- package/vendor/dsh-bili-scroll/index.js +15 -6
- package/vendor/dsh-bili-scroll/prompts/duty.md +6 -3
package/lib/setup.mjs
ADDED
|
@@ -0,0 +1,431 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* setup.mjs —— 「一键安装全部依赖」的编排器(macOS / Windows / Linux)。
|
|
3
|
+
*
|
|
4
|
+
* 用户只点一次;这里按**固定顺序**一步一步跑,每一步都能单独看到状态与日志:
|
|
5
|
+
* 1. uv —— 单个可执行文件;没有就自己下一个(GitHub → PyPI 清华镜像)
|
|
6
|
+
* 2. bili-venv —— Python 3.12 venv + B站 MCP 依赖(bilibili-api / mcp / qrcode / Pillow)
|
|
7
|
+
* 3. dashscope —— Sambert 语音要用的 Python SDK(装进同一个 venv)
|
|
8
|
+
* 4. ffmpeg —— 视频分镜 / 语音转码要用的系统工具(winget / brew / apt)
|
|
9
|
+
* 5. yt-dlp —— 视频分镜拉 B站 视频用(uv tool 或 pip --user)
|
|
10
|
+
* 6. qwen3-tts —— 可选:本地 Qwen3-TTS 环境(要下模型,几分钟到几十分钟)
|
|
11
|
+
*
|
|
12
|
+
* 顺序是有原因的:后面几步要用前面的产物(venv 要用 uv 建;dashscope 要装进 venv;
|
|
13
|
+
* yt-dlp 优先用 uv tool)。
|
|
14
|
+
*/
|
|
15
|
+
import { spawn } from 'node:child_process'
|
|
16
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'
|
|
17
|
+
import { homedir } from 'node:os'
|
|
18
|
+
import { delimiter, dirname, join } from 'node:path'
|
|
19
|
+
import { fileURLToPath } from 'node:url'
|
|
20
|
+
|
|
21
|
+
import { ensureUv } from '../vendor/dsh-bili-scroll/lib/uvfetch.mjs'
|
|
22
|
+
import { PIP_MIRRORS, pickPipMirror } from './net.mjs'
|
|
23
|
+
|
|
24
|
+
const HOME = () => String(process.env.DSH_HOME || '').trim() || join(homedir(), '.dsh')
|
|
25
|
+
const LOG_MAX = 3000
|
|
26
|
+
|
|
27
|
+
function dshHome() { return HOME() }
|
|
28
|
+
function biliDir() { return join(dshHome(), 'bili-duty') }
|
|
29
|
+
function venvDir() { return join(biliDir(), '.venv') }
|
|
30
|
+
function venvPython() {
|
|
31
|
+
return process.platform === 'win32'
|
|
32
|
+
? join(venvDir(), 'Scripts', 'python.exe')
|
|
33
|
+
: join(venvDir(), 'bin', 'python')
|
|
34
|
+
}
|
|
35
|
+
function reqFile() {
|
|
36
|
+
return join(dirname(fileURLToPath(import.meta.url)), '..', 'vendor', 'dsh-bili-scroll', 'vendor', 'bilibili-mcp', 'requirements.txt')
|
|
37
|
+
}
|
|
38
|
+
function uvDir() { return join(dshHome(), 'companion', 'bin') }
|
|
39
|
+
function setupLog() { return join(dshHome(), 'companion', 'setup.log') }
|
|
40
|
+
|
|
41
|
+
function run(cmd, args, { cwd = dshHome(), env = {}, timeout = 30 * 60_000 } = {}) {
|
|
42
|
+
return new Promise((resolve) => {
|
|
43
|
+
let out = ''
|
|
44
|
+
let child
|
|
45
|
+
const sink = (b) => { out += String(b); if (out.length > 200_000) out = out.slice(-120_000) }
|
|
46
|
+
try {
|
|
47
|
+
child = spawn(cmd, args, { cwd, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, ...env } })
|
|
48
|
+
} catch (error) {
|
|
49
|
+
resolve({ status: -1, output: String((error && error.message) || error) })
|
|
50
|
+
return
|
|
51
|
+
}
|
|
52
|
+
const timer = setTimeout(() => { try { child.kill() } catch { /* ignore */ } }, timeout)
|
|
53
|
+
child.stdout?.on('data', sink)
|
|
54
|
+
child.stderr?.on('data', sink)
|
|
55
|
+
child.on('error', (error) => { clearTimeout(timer); resolve({ status: -1, output: out + '\n' + String((error && error.message) || error) }) })
|
|
56
|
+
child.on('exit', (code) => { clearTimeout(timer); resolve({ status: code === null ? -1 : code, output: out }) })
|
|
57
|
+
})
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** 下载到文件(跟随跳转,带超时与大文件保护)。返回 { ok, bytes, error }。 */
|
|
61
|
+
async function downloadTo(url, file, { timeoutMs = 15 * 60_000, maxBytes = 300 * 1024 * 1024 } = {}) {
|
|
62
|
+
const controller = new AbortController()
|
|
63
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs)
|
|
64
|
+
try {
|
|
65
|
+
const r = await fetch(url, { signal: controller.signal, redirect: 'follow' })
|
|
66
|
+
if (!r.ok) return { ok: false, bytes: 0, error: 'HTTP ' + r.status }
|
|
67
|
+
const chunks = []
|
|
68
|
+
let total = 0
|
|
69
|
+
if (r.body) {
|
|
70
|
+
const reader = r.body.getReader()
|
|
71
|
+
for (;;) {
|
|
72
|
+
const { done, value } = await reader.read()
|
|
73
|
+
if (done) break
|
|
74
|
+
total += value ? value.length : 0
|
|
75
|
+
if (total > maxBytes) { try { reader.cancel() } catch { /* ignore */ } return { ok: false, bytes: total, error: '文件超过 ' + Math.round(maxBytes / 1048576) + 'MB' } }
|
|
76
|
+
chunks.push(Buffer.from(value))
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
80
|
+
writeFileSync(file, Buffer.concat(chunks))
|
|
81
|
+
return { ok: true, bytes: total, error: '' }
|
|
82
|
+
} catch (error) {
|
|
83
|
+
return { ok: false, bytes: 0, error: String((error && error.message) || error) }
|
|
84
|
+
} finally {
|
|
85
|
+
clearTimeout(timer)
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** ffmpeg 只认 `-version`(单横线);`--version` 会 exit 8,别拿它判断。 */
|
|
90
|
+
async function ffmpegOk(cmd = 'ffmpeg') {
|
|
91
|
+
return (await probe(cmd, ['-version']))
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function probe(cmd, args = ['--version']) {
|
|
95
|
+
return runningPromise(cmd, args)
|
|
96
|
+
}
|
|
97
|
+
function runningPromise(cmd, args) {
|
|
98
|
+
return new Promise((resolve) => {
|
|
99
|
+
let child
|
|
100
|
+
try { child = spawn(cmd, args, { windowsHide: true, stdio: 'ignore' }) } catch { resolve(false); return }
|
|
101
|
+
child.on('error', () => resolve(false))
|
|
102
|
+
child.on('exit', (code) => resolve(code === 0))
|
|
103
|
+
})
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async function findUv() {
|
|
107
|
+
const win = process.platform === 'win32'
|
|
108
|
+
const candidates = [
|
|
109
|
+
join(uvDir(), win ? 'uv.exe' : 'uv'),
|
|
110
|
+
join(homedir(), '.local', 'bin', win ? 'uv.exe' : 'uv'),
|
|
111
|
+
win ? 'uv.exe' : 'uv',
|
|
112
|
+
]
|
|
113
|
+
for (const cmd of candidates) {
|
|
114
|
+
if (cmd.includes('/') || cmd.includes('\\')) { if (!existsSync(cmd)) continue }
|
|
115
|
+
if (await probe(cmd)) return cmd
|
|
116
|
+
}
|
|
117
|
+
return ''
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** 静态版 ffmpeg:直接下压缩包解到 ~/.dsh/companion/bin,挑最快的镜像。 */
|
|
121
|
+
async function installStaticFfmpeg(ctx) {
|
|
122
|
+
const dir = join(dshHome(), 'companion', 'bin')
|
|
123
|
+
const win = process.platform === 'win32'
|
|
124
|
+
const bases = [
|
|
125
|
+
'https://ghfast.top/https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/',
|
|
126
|
+
'https://gh-proxy.com/https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/',
|
|
127
|
+
'https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/',
|
|
128
|
+
]
|
|
129
|
+
const asset = win ? 'ffmpeg-master-latest-win64-gpl.zip' : 'ffmpeg-master-latest-linux64-gpl.tar.xz'
|
|
130
|
+
// 先挑一个能连上的镜像
|
|
131
|
+
let base = ''
|
|
132
|
+
for (const b of bases) {
|
|
133
|
+
ctx.log('测镜像:' + b.split('/')[2])
|
|
134
|
+
const p = await probe(b + asset, { timeoutMs: 6000, maxBytes: 32 * 1024 })
|
|
135
|
+
if (p.ok) { base = b; break }
|
|
136
|
+
}
|
|
137
|
+
if (base === '') return { ok: false, detail: '镜像都不通' }
|
|
138
|
+
const archive = join(dir, asset)
|
|
139
|
+
ctx.log('下载 ' + asset + ' …')
|
|
140
|
+
const dl = await downloadTo(base + asset, archive)
|
|
141
|
+
if (!dl.ok) return { ok: false, detail: '下载失败:' + dl.error }
|
|
142
|
+
ctx.log('已下载 ' + Math.round(dl.bytes / 1048576) + 'MB,解压…')
|
|
143
|
+
const extract = await run('tar', ['-xf', archive, '-C', dir])
|
|
144
|
+
ctx.log(extract.output)
|
|
145
|
+
// 在解压出来的树里找 ffmpeg 可执行文件,拷到 bin 根
|
|
146
|
+
const found = findFile(dir, win ? 'ffmpeg.exe' : 'ffmpeg', 4)
|
|
147
|
+
if (found === null) return { ok: false, detail: '解压后没找到 ffmpeg' }
|
|
148
|
+
const target = join(dir, win ? 'ffmpeg.exe' : 'ffmpeg')
|
|
149
|
+
if (found !== target) {
|
|
150
|
+
try { writeFileSync(target, readFileSync(found)); chmodSync(target, 0o755) } catch { /* 直接用它也行 */ }
|
|
151
|
+
}
|
|
152
|
+
if (await ffmpegOk(target)) return { ok: true, detail: target }
|
|
153
|
+
return { ok: false, detail: '装好了但跑不起来(缺少系统库)', hint: target }
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** 在目录里找文件名(限深度),找不到返回 null。 */
|
|
157
|
+
function findFile(dir, name, depth) {
|
|
158
|
+
if (depth < 0) return null
|
|
159
|
+
let entries = []
|
|
160
|
+
try { entries = readdirSync(dir, { withFileTypes: true }) } catch { return null }
|
|
161
|
+
for (const e of entries) {
|
|
162
|
+
const full = join(dir, e.name)
|
|
163
|
+
if (e.isFile() && e.name === name) return full
|
|
164
|
+
if (e.isDirectory()) { const hit = findFile(full, name, depth - 1); if (hit !== null) return hit }
|
|
165
|
+
}
|
|
166
|
+
return null
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** 步骤定义:顺序 + 判定「已经好了吗」+ 执行。 */
|
|
170
|
+
export const STEPS = [
|
|
171
|
+
{
|
|
172
|
+
id: 'net', label: '网速探测(自动选最快的源)', required: false,
|
|
173
|
+
async check() { return false },
|
|
174
|
+
async run(ctx) {
|
|
175
|
+
const picked = await pickPipMirror({ force: true, log: (m) => ctx.log(m) })
|
|
176
|
+
return { ok: true, detail: picked.label + ' · ' + picked.kbps + ' KB/s(' + picked.reason + ')' }
|
|
177
|
+
},
|
|
178
|
+
},
|
|
179
|
+
{
|
|
180
|
+
id: 'uv', label: 'uv(Python 环境工具)', required: true,
|
|
181
|
+
async check() { return (await findUv()) !== '' },
|
|
182
|
+
async run(ctx) {
|
|
183
|
+
const found = await findUv()
|
|
184
|
+
if (found !== '') return { ok: true, detail: found }
|
|
185
|
+
const got = await ensureUv({ dir: uvDir(), log: (m) => ctx.log(m) })
|
|
186
|
+
const uv = got && (got.cmd || got.path)
|
|
187
|
+
if (!uv) return { ok: false, detail: '没下到 uv(网络到不了 GitHub / PyPI 镜像)', hint: winHint('uv') }
|
|
188
|
+
return { ok: true, detail: String(uv) }
|
|
189
|
+
},
|
|
190
|
+
},
|
|
191
|
+
{
|
|
192
|
+
id: 'bili-venv', label: 'B站 Python 环境(venv + MCP 依赖)', required: true,
|
|
193
|
+
async check() {
|
|
194
|
+
const py = venvPython()
|
|
195
|
+
if (!existsSync(py)) return false
|
|
196
|
+
// 光有 python 不算好:关键依赖要真的 import 得进来
|
|
197
|
+
const r = await run(py, ['-c', 'import bilibili_api, mcp, qrcode, PIL; print("ok")'], { timeout: 60_000 })
|
|
198
|
+
return r.status === 0
|
|
199
|
+
},
|
|
200
|
+
async run(ctx) {
|
|
201
|
+
const uv = await findUv()
|
|
202
|
+
if (uv === '') return { ok: false, detail: '没有 uv,先跑第 1 步' }
|
|
203
|
+
mkdirSync(biliDir(), { recursive: true })
|
|
204
|
+
if (!existsSync(venvPython())) {
|
|
205
|
+
const v = await run(uv, ['venv', '--seed', '--python', '3.12', venvDir()])
|
|
206
|
+
ctx.log(v.output)
|
|
207
|
+
if (v.status !== 0) {
|
|
208
|
+
const v2 = await run(uv, ['venv', '--seed', venvDir()])
|
|
209
|
+
ctx.log(v2.output)
|
|
210
|
+
if (v2.status !== 0) return { ok: false, detail: '建 venv 失败(两条路都试过)' }
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
const py = venvPython()
|
|
214
|
+
// 先测网速选最快的源,再按「快 → 次快」依次重试,尽量一次装成
|
|
215
|
+
const picked = await pickPipMirror({ log: (m) => ctx.log(m) })
|
|
216
|
+
const order = [picked.url, ...PIP_MIRRORS.map((m) => m.url).filter((u) => u !== picked.url)]
|
|
217
|
+
let last = ''
|
|
218
|
+
for (const m of order) {
|
|
219
|
+
ctx.log('用镜像:' + m)
|
|
220
|
+
const r = await run(uv, ['pip', 'install', '--python', py, '-i', m, '-r', reqFile()])
|
|
221
|
+
ctx.log(r.output)
|
|
222
|
+
last = r.output
|
|
223
|
+
if (r.status === 0) {
|
|
224
|
+
// 装完再验一次「真的能 import」——有的镜像会缺包但返回 0
|
|
225
|
+
const verify = await run(py, ['-c', 'import bilibili_api, mcp, qrcode, PIL; print("ok")'], { timeout: 60_000 })
|
|
226
|
+
ctx.log(verify.output)
|
|
227
|
+
if (verify.status === 0) return { ok: true, detail: '依赖已装好(' + picked.label + ',' + picked.kbps + ' KB/s)' }
|
|
228
|
+
ctx.log('装完验不过,换下一个镜像重试')
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
return { ok: false, detail: '依赖没装上(所有镜像都失败)', output: last.slice(-800) }
|
|
232
|
+
},
|
|
233
|
+
},
|
|
234
|
+
{
|
|
235
|
+
id: 'dashscope', label: 'dashscope(Sambert 语音)', required: false,
|
|
236
|
+
async check() {
|
|
237
|
+
const py = venvPython()
|
|
238
|
+
if (!existsSync(py)) return false
|
|
239
|
+
const r = await run(py, ['-c', 'import dashscope'])
|
|
240
|
+
return r.status === 0
|
|
241
|
+
},
|
|
242
|
+
async run(ctx) {
|
|
243
|
+
const py = venvPython()
|
|
244
|
+
if (!existsSync(py)) return { ok: false, detail: '还没有 venv(先跑第 2 步)' }
|
|
245
|
+
const uv = await findUv()
|
|
246
|
+
const picked = await pickPipMirror({ log: (m) => ctx.log(m) })
|
|
247
|
+
const cmds = uv !== ''
|
|
248
|
+
? [[uv, ['pip', 'install', '--python', py, '-i', picked.url, 'dashscope']], [uv, ['pip', 'install', '--python', py, '-i', PIP_MIRRORS[1].url, 'dashscope']]]
|
|
249
|
+
: [[py, ['-m', 'pip', 'install', '-i', picked.url, '-U', 'dashscope']], [py, ['-m', 'pip', 'install', '-i', PIP_MIRRORS[1].url, '-U', 'dashscope']]]
|
|
250
|
+
for (const [cmd, args] of cmds) {
|
|
251
|
+
const r = await run(cmd, args)
|
|
252
|
+
ctx.log(r.output)
|
|
253
|
+
if (r.status === 0) {
|
|
254
|
+
const check = await run(py, ['-c', 'import dashscope; print(dashscope.__version__)'])
|
|
255
|
+
if (check.status === 0) return { ok: true, detail: String(check.output).trim().slice(0, 40) }
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
return { ok: false, detail: '装 dashscope 失败' }
|
|
259
|
+
},
|
|
260
|
+
},
|
|
261
|
+
{
|
|
262
|
+
id: 'ffmpeg', label: 'ffmpeg(视频分镜 / 音频转码)', required: false,
|
|
263
|
+
async check() { return (await ffmpegOk()) },
|
|
264
|
+
async run(ctx) {
|
|
265
|
+
const attempts = []
|
|
266
|
+
if (process.platform === 'win32') {
|
|
267
|
+
attempts.push(['winget', ['install', '--id', 'Gyan.FFmpeg', '-e', '--accept-source-agreements', '--accept-package-agreements']])
|
|
268
|
+
} else if (process.platform === 'darwin') {
|
|
269
|
+
if (await probe('brew')) attempts.push(['brew', ['install', 'ffmpeg']])
|
|
270
|
+
} else {
|
|
271
|
+
attempts.push(['sudo', ['-n', 'apt-get', 'install', '-y', 'ffmpeg']])
|
|
272
|
+
attempts.push(['apt-get', ['install', '-y', 'ffmpeg']])
|
|
273
|
+
}
|
|
274
|
+
for (const [cmd, args] of attempts) {
|
|
275
|
+
ctx.log('$ ' + cmd + ' ' + args.join(' '))
|
|
276
|
+
const r = await run(cmd, args)
|
|
277
|
+
ctx.log(r.output)
|
|
278
|
+
if (await ffmpegOk()) return { ok: true, detail: '已安装' }
|
|
279
|
+
}
|
|
280
|
+
// 包管理器不行 → 试静态构建(带 GitHub 加速镜像),只支持 Windows / Linux
|
|
281
|
+
if (process.platform !== 'darwin') {
|
|
282
|
+
const got = await installStaticFfmpeg(ctx)
|
|
283
|
+
if (got.ok) return got
|
|
284
|
+
}
|
|
285
|
+
return {
|
|
286
|
+
ok: false, detail: '自动装不上,请手动装',
|
|
287
|
+
hint: process.platform === 'win32' ? 'winget install Gyan.FFmpeg'
|
|
288
|
+
: process.platform === 'darwin' ? 'brew install ffmpeg'
|
|
289
|
+
: 'sudo apt install ffmpeg(或你的发行版的包管理器)',
|
|
290
|
+
}
|
|
291
|
+
},
|
|
292
|
+
},
|
|
293
|
+
{
|
|
294
|
+
id: 'yt-dlp', label: 'yt-dlp(视频分镜拉 B站 视频)', required: false,
|
|
295
|
+
async check() { return (await probe('yt-dlp')) },
|
|
296
|
+
async run(ctx) {
|
|
297
|
+
const uv = await findUv()
|
|
298
|
+
const picked = await pickPipMirror({ log: (m) => ctx.log(m) })
|
|
299
|
+
if (uv !== '') {
|
|
300
|
+
const r = await run(uv, ['tool', 'install', '--upgrade', '--index-url', picked.url, 'yt-dlp'])
|
|
301
|
+
ctx.log(r.output)
|
|
302
|
+
if (await probe('yt-dlp')) return { ok: true, detail: 'uv tool 已装(' + picked.label + ')' }
|
|
303
|
+
}
|
|
304
|
+
const py = venvPython()
|
|
305
|
+
if (existsSync(py)) {
|
|
306
|
+
const r = await run(py, ['-m', 'pip', 'install', '-i', picked.url, '-U', 'yt-dlp'])
|
|
307
|
+
ctx.log(r.output)
|
|
308
|
+
const local = process.platform === 'win32' ? join(venvDir(), 'Scripts', 'yt-dlp.exe') : join(venvDir(), 'bin', 'yt-dlp')
|
|
309
|
+
if (existsSync(local)) return { ok: true, detail: local }
|
|
310
|
+
}
|
|
311
|
+
return { ok: false, detail: '装不上 yt-dlp', hint: 'uv tool install yt-dlp' }
|
|
312
|
+
},
|
|
313
|
+
},
|
|
314
|
+
{
|
|
315
|
+
id: 'qwen3-tts', label: '本地 Qwen3-TTS(可选,要下模型)', required: false, optional: true,
|
|
316
|
+
async check() { return existsSync(join(dshHome(), 'tts-qwen3')) },
|
|
317
|
+
async run() {
|
|
318
|
+
return { ok: false, skipped: true, detail: '可选:到「语音」页点「装环境 / 启动」再装(要下载模型)' }
|
|
319
|
+
},
|
|
320
|
+
},
|
|
321
|
+
]
|
|
322
|
+
|
|
323
|
+
function winHint(what) {
|
|
324
|
+
if (what === 'uv') {
|
|
325
|
+
return process.platform === 'win32'
|
|
326
|
+
? 'powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"'
|
|
327
|
+
: 'curl -LsSf https://astral.sh/uv/install.sh | sh'
|
|
328
|
+
}
|
|
329
|
+
return ''
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/** 编排状态(内存 + 落盘日志)。 */
|
|
333
|
+
const state = {
|
|
334
|
+
running: false,
|
|
335
|
+
startedAt: null,
|
|
336
|
+
finishedAt: null,
|
|
337
|
+
current: '',
|
|
338
|
+
steps: STEPS.map((s) => ({ id: s.id, label: s.label, required: s.required === true, optional: s.optional === true, state: 'pending', detail: '', hint: '', log: '', ms: 0 })),
|
|
339
|
+
}
|
|
340
|
+
let chain = null
|
|
341
|
+
|
|
342
|
+
function persist() {
|
|
343
|
+
try {
|
|
344
|
+
mkdirSync(dirname(setupLog()), { recursive: true })
|
|
345
|
+
writeFileSync(setupLog(), JSON.stringify({ at: new Date().toISOString(), ...snapshot() }, null, 2), 'utf8')
|
|
346
|
+
} catch { /* 日志写不了不影响安装 */ }
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
function snapshot() {
|
|
350
|
+
return {
|
|
351
|
+
running: state.running,
|
|
352
|
+
startedAt: state.startedAt,
|
|
353
|
+
finishedAt: state.finishedAt,
|
|
354
|
+
current: state.current,
|
|
355
|
+
steps: state.steps.map((s) => ({ ...s, log: s.log.slice(-LOG_MAX) })),
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
export function setupStatus() { return snapshot() }
|
|
360
|
+
|
|
361
|
+
export function isSetupRunning() { return state.running }
|
|
362
|
+
|
|
363
|
+
/** 只体检、不安装:按顺序返回每一步现在是否已就绪。 */
|
|
364
|
+
export async function setupPlan() {
|
|
365
|
+
const out = []
|
|
366
|
+
for (const step of STEPS) {
|
|
367
|
+
let ok = false
|
|
368
|
+
try { ok = await step.check() } catch { ok = false }
|
|
369
|
+
out.push({ id: step.id, label: step.label, required: step.required === true, optional: step.optional === true, ok })
|
|
370
|
+
}
|
|
371
|
+
return out
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/** 一键安装(幂等:已经就绪的步骤会跳过)。同一时间只跑一份。 */
|
|
375
|
+
export function runSetup({ only = [] } = {}) {
|
|
376
|
+
if (state.running) return { ok: true, busy: true, ...snapshot() }
|
|
377
|
+
state.running = true
|
|
378
|
+
state.startedAt = new Date().toISOString()
|
|
379
|
+
state.finishedAt = null
|
|
380
|
+
state.current = ''
|
|
381
|
+
for (const s of state.steps) { s.state = 'pending'; s.detail = ''; s.hint = ''; s.log = ''; s.ms = 0 }
|
|
382
|
+
persist()
|
|
383
|
+
|
|
384
|
+
chain = (async () => {
|
|
385
|
+
for (let i = 0; i < STEPS.length; i++) {
|
|
386
|
+
const step = STEPS[i]
|
|
387
|
+
const row = state.steps[i]
|
|
388
|
+
if (only.length > 0 && !only.includes(step.id)) { row.state = 'skipped'; continue }
|
|
389
|
+
const startedAt = Date.now()
|
|
390
|
+
row.state = 'running'
|
|
391
|
+
state.current = step.id
|
|
392
|
+
persist()
|
|
393
|
+
try {
|
|
394
|
+
const ready = await step.check().catch(() => false)
|
|
395
|
+
if (ready) {
|
|
396
|
+
row.state = 'ok'
|
|
397
|
+
row.detail = '已就绪,跳过'
|
|
398
|
+
} else {
|
|
399
|
+
const ctx = { log: (m) => { if (m) { row.log = (row.log + '\n' + String(m)).slice(-LOG_MAX); persist() } } }
|
|
400
|
+
const r = await step.run(ctx)
|
|
401
|
+
if (r && r.skipped) { row.state = 'skipped'; row.detail = String(r.detail || '') }
|
|
402
|
+
else if (r && r.ok) { row.state = 'ok'; row.detail = String(r.detail || '完成') }
|
|
403
|
+
else {
|
|
404
|
+
row.state = 'failed'
|
|
405
|
+
row.detail = String((r && r.detail) || '失败')
|
|
406
|
+
row.hint = String((r && r.hint) || '')
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
} catch (error) {
|
|
410
|
+
row.state = 'failed'
|
|
411
|
+
row.detail = String((error && error.message) || error)
|
|
412
|
+
}
|
|
413
|
+
row.ms = Date.now() - startedAt
|
|
414
|
+
persist()
|
|
415
|
+
}
|
|
416
|
+
state.current = ''
|
|
417
|
+
state.running = false
|
|
418
|
+
state.finishedAt = new Date().toISOString()
|
|
419
|
+
persist()
|
|
420
|
+
try {
|
|
421
|
+
const tail = state.steps.map((s) => `${s.label}: ${s.state}${s.detail ? ' — ' + s.detail : ''}`).join('\n')
|
|
422
|
+
console.log('[companion] 依赖安装结束\n' + tail)
|
|
423
|
+
} catch { /* ignore */ }
|
|
424
|
+
})().catch((error) => {
|
|
425
|
+
state.running = false
|
|
426
|
+
state.finishedAt = new Date().toISOString()
|
|
427
|
+
console.log('[companion] 依赖安装异常:' + String((error && error.message) || error))
|
|
428
|
+
persist()
|
|
429
|
+
})
|
|
430
|
+
return { ok: true, started: true, ...snapshot() }
|
|
431
|
+
}
|
package/package.json
CHANGED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* chat-models.js —— 按「QQ 会话」指定模型(私聊 / 每个群各自一份)。
|
|
3
|
+
*
|
|
4
|
+
* 背景(2026-11-07 用户要求):QQ 接进来的每个私聊/群都是一个独立对话,
|
|
5
|
+
* 希望它们各自能用 DSH 里已经配置好的某个 provider 的某个 model。
|
|
6
|
+
*
|
|
7
|
+
* 做法:
|
|
8
|
+
* - 登记表 `<agentsRoot>/chat-models.json`:`<peerKey> → { provider, model, reasoningEffort? }`
|
|
9
|
+
* - `agent/created` 时按会话 id 反查 peerKey,命中就 `agent.model.select(...)`,
|
|
10
|
+
* 只影响这个会话,不动全局默认模型。
|
|
11
|
+
*/
|
|
12
|
+
import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs'
|
|
13
|
+
import { join } from 'node:path'
|
|
14
|
+
|
|
15
|
+
import { agentsRoot } from './persona.js'
|
|
16
|
+
import { peerKeyForSession, parsePeerKey, readQqSessions } from './chat-persona.js'
|
|
17
|
+
|
|
18
|
+
export function chatModelsPath() {
|
|
19
|
+
return join(agentsRoot(), 'chat-models.json')
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function readChatModels() {
|
|
23
|
+
try {
|
|
24
|
+
const parsed = JSON.parse(readFileSync(chatModelsPath(), 'utf8'))
|
|
25
|
+
return parsed !== null && typeof parsed === 'object' ? parsed : {}
|
|
26
|
+
} catch {
|
|
27
|
+
return {}
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function writeChatModels(registry) {
|
|
32
|
+
const file = chatModelsPath()
|
|
33
|
+
mkdirSync(agentsRoot(), { recursive: true })
|
|
34
|
+
const body = `${JSON.stringify(registry, null, 2)}\n`
|
|
35
|
+
const tmp = `${file}.tmp-${process.pid}`
|
|
36
|
+
writeFileSync(tmp, body, 'utf8')
|
|
37
|
+
try {
|
|
38
|
+
writeFileSync(file, readFileSync(tmp))
|
|
39
|
+
unlinkSync(tmp)
|
|
40
|
+
} catch {
|
|
41
|
+
writeFileSync(file, body, 'utf8')
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** 全局默认模型(由 dsh-chat-comprehension 写入;没有返回 null)。 */
|
|
46
|
+
export function globalModel() {
|
|
47
|
+
try {
|
|
48
|
+
const parsed = JSON.parse(readFileSync(join(agentsRoot(), 'companion-model.json'), 'utf8'))
|
|
49
|
+
const provider = String(parsed?.provider || '').trim()
|
|
50
|
+
const model = String(parsed?.model || '').trim()
|
|
51
|
+
if (provider === '' || model === '') return null
|
|
52
|
+
const reasoningEffort = String(parsed?.reasoningEffort || '').trim()
|
|
53
|
+
return { provider, model, ...(reasoningEffort !== '' ? { reasoningEffort } : {}) }
|
|
54
|
+
} catch {
|
|
55
|
+
return null
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** 这个会话被指定的模型选择(没有返回 null)。 */
|
|
60
|
+
export function chatModelForSession(sessionId) {
|
|
61
|
+
const peerKey = peerKeyForSession(sessionId)
|
|
62
|
+
if (peerKey === '') return null
|
|
63
|
+
const entry = readChatModels()[peerKey]
|
|
64
|
+
if (entry === null || typeof entry !== 'object') return null
|
|
65
|
+
const provider = String(entry.provider || '').trim()
|
|
66
|
+
const model = String(entry.model || '').trim()
|
|
67
|
+
if (provider === '' || model === '') return null
|
|
68
|
+
const reasoningEffort = String(entry.reasoningEffort || '').trim()
|
|
69
|
+
return { peerKey, provider, model, ...(reasoningEffort !== '' ? { reasoningEffort } : {}) }
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** 保存一个会话的模型(provider/model 必须非空)。 */
|
|
73
|
+
export function saveChatModel(peerKey, selection) {
|
|
74
|
+
if (typeof peerKey !== 'string' || peerKey.trim() === '') throw Object.assign(new Error('缺少 peerKey'), { status: 400 })
|
|
75
|
+
const provider = String(selection?.provider || '').trim()
|
|
76
|
+
const model = String(selection?.model || '').trim()
|
|
77
|
+
if (provider === '' || model === '') throw Object.assign(new Error('provider 和 model 都要填'), { status: 400 })
|
|
78
|
+
const reasoningEffort = String(selection?.reasoningEffort || '').trim()
|
|
79
|
+
const registry = readChatModels()
|
|
80
|
+
registry[peerKey] = {
|
|
81
|
+
...(parsePeerKey(peerKey) || {}),
|
|
82
|
+
provider,
|
|
83
|
+
model,
|
|
84
|
+
...(reasoningEffort !== '' ? { reasoningEffort } : {}),
|
|
85
|
+
updatedAt: new Date().toISOString(),
|
|
86
|
+
}
|
|
87
|
+
writeChatModels(registry)
|
|
88
|
+
return { ok: true, selection: registry[peerKey] }
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function removeChatModel(peerKey) {
|
|
92
|
+
const registry = readChatModels()
|
|
93
|
+
if (registry[peerKey] !== undefined) {
|
|
94
|
+
delete registry[peerKey]
|
|
95
|
+
writeChatModels(registry)
|
|
96
|
+
}
|
|
97
|
+
return { ok: true }
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** 列出所有 QQ 会话 + 它们各自的模型(给设置页用)。 */
|
|
101
|
+
export function listChatModels() {
|
|
102
|
+
const sessions = readQqSessions()
|
|
103
|
+
const registry = readChatModels()
|
|
104
|
+
return Object.keys(sessions).map((peerKey) => {
|
|
105
|
+
const entry = registry[peerKey] || {}
|
|
106
|
+
return {
|
|
107
|
+
peerKey,
|
|
108
|
+
...(parsePeerKey(peerKey) || {}),
|
|
109
|
+
sessionId: String(sessions[peerKey] || ''),
|
|
110
|
+
provider: String(entry.provider || ''),
|
|
111
|
+
model: String(entry.model || ''),
|
|
112
|
+
reasoningEffort: String(entry.reasoningEffort || ''),
|
|
113
|
+
updatedAt: entry.updatedAt || null,
|
|
114
|
+
}
|
|
115
|
+
})
|
|
116
|
+
}
|