@yangzhenghan/dsh-bluewhale 0.0.0-stage → 0.3.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.
- package/LICENSE +21 -0
- package/README.md +47 -3
- package/assets/silero-vad.onnx +0 -0
- package/cordis.patch.yml +8 -0
- package/icon.png +0 -0
- package/index.js +121 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +16 -4
- package/src/clean-text.js +60 -0
- package/src/cookie-cleaner.js +92 -0
- package/src/dsh.js +102 -0
- package/src/followups.js +68 -0
- package/src/helpers.js +36 -0
- package/src/idle-motion.js +13 -0
- package/src/outfit.js +32 -0
- package/src/pet-download.js +153 -0
- package/src/pet-rules.js +24 -0
- package/src/pet.js +48 -0
- package/src/route.js +43 -0
- package/src/server.js +207 -0
- package/src/sessions.js +50 -0
- package/src/state.js +43 -0
- package/src/vad-mirror.js +97 -0
- package/src/vision.js +82 -0
- package//346/241/214/345/256/240/350/247/204/345/210/231.md +4 -0
package/src/outfit.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// 换装用动作代替表情:AIRI 同一时间只有一个表情,换装表情会被下一个表情清掉
|
|
2
|
+
// 把换装表情换成同名的换装动作(Animation/换装-xxx.motion3.json),衣服就能一直保持
|
|
3
|
+
// 换回原样的 {"expression":null} 换成「换装-全部还原」;单件换回用穿鞋、短裙这些名字(模型里没有这些表情,只有动作)
|
|
4
|
+
|
|
5
|
+
const OUTFITS = new Set([
|
|
6
|
+
'长裙', '中号', '小号', '大号', '脱鞋', '尾巴开关', '胸口衣服',
|
|
7
|
+
'穿鞋', '短裙', '放出尾巴', '换回胸口衣服',
|
|
8
|
+
])
|
|
9
|
+
// 旧名字:裙子切换 = 换长裙,换回裙子 = 换短裙,体型1/体型2/默认体型 = 中号/小号/大号
|
|
10
|
+
const ALIASES = { 裙子切换: '长裙', 换回裙子: '短裙', 体型1: '中号', 体型2: '小号', 默认体型: '大号' }
|
|
11
|
+
const outfitMotion = (name) => `Animation/换装-${name}.motion3.json`
|
|
12
|
+
|
|
13
|
+
export function withOutfitMotions(reply, enabled) {
|
|
14
|
+
if (!reply || !enabled) return reply
|
|
15
|
+
return reply.replace(/<\|ACT\s+([\s\S]*?)\|>/g, (tag, body) => {
|
|
16
|
+
let act
|
|
17
|
+
try {
|
|
18
|
+
act = JSON.parse(body)
|
|
19
|
+
} catch {
|
|
20
|
+
return tag
|
|
21
|
+
}
|
|
22
|
+
if (!act || typeof act !== 'object' || !('expression' in act)) return tag
|
|
23
|
+
const { expression, ...rest } = act
|
|
24
|
+
let name
|
|
25
|
+
if (expression === null) name = '全部还原'
|
|
26
|
+
else if (OUTFITS.has(expression?.name)) name = expression.name
|
|
27
|
+
else if (ALIASES[expression?.name]) name = ALIASES[expression.name]
|
|
28
|
+
else return tag
|
|
29
|
+
// 换装动作里带着说话晃动,同一个标记里角色写的姿势让给换装
|
|
30
|
+
return `<|ACT ${JSON.stringify({ ...rest, motion: outfitMotion(name) })}|>`
|
|
31
|
+
})
|
|
32
|
+
}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
// 第一次用时自动下载桌宠:npm 上的插件只有几十 KB,桌宠程序(带大肥鱼模型)约 460MB,放在 Gitee / GitHub 的发行版里
|
|
2
|
+
// 顺序:先 Gitee(国内快,5 个分卷),不行再 GitHub(整包);下完核对 SHA-256,解压出 桌宠\ 放到 ~/.dsh/blue-whale/pet-<版本>\
|
|
3
|
+
// 下到一半断了:已经下好的分卷下次接着用;整包对不上就删掉重下
|
|
4
|
+
import fs from 'node:fs'
|
|
5
|
+
import os from 'node:os'
|
|
6
|
+
import path from 'node:path'
|
|
7
|
+
import crypto from 'node:crypto'
|
|
8
|
+
import { execFile } from 'node:child_process'
|
|
9
|
+
import { log } from './state.js'
|
|
10
|
+
|
|
11
|
+
// 要下的桌宠版本。换了桌宠就改这里(大小、指纹、地址都要一起改)
|
|
12
|
+
export const PET = {
|
|
13
|
+
version: '0.3.0',
|
|
14
|
+
size: 486806670,
|
|
15
|
+
sha256: 'add3c8768c0c453cbe212919fb9a19d5a8c527f8fb53a972f3b66b02dcfa0a03',
|
|
16
|
+
// 包里桌宠所在的文件夹
|
|
17
|
+
inner: path.join('blue-whale', '桌宠'),
|
|
18
|
+
sources: [
|
|
19
|
+
{
|
|
20
|
+
name: 'Gitee',
|
|
21
|
+
parts: [1, 2, 3, 4, 5].map((i) => `https://gitee.com/yangzhenghan/blue-whale/releases/download/v0.3.0/blue-whale-v0.3.0.zip.00${i}`),
|
|
22
|
+
},
|
|
23
|
+
{
|
|
24
|
+
name: 'GitHub',
|
|
25
|
+
parts: ['https://github.com/yangzhenghaniirs-code/blue-whale/releases/download/v0.3.0/blue-whale-v0.3.0.zip'],
|
|
26
|
+
},
|
|
27
|
+
],
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export const PET_HOME = path.join(os.homedir(), '.dsh', 'blue-whale')
|
|
31
|
+
export const PET_DIR = path.join(PET_HOME, `pet-${PET.version}`)
|
|
32
|
+
export const PET_EXE = path.join(PET_DIR, '桌宠', 'airi.exe')
|
|
33
|
+
|
|
34
|
+
let running = null
|
|
35
|
+
|
|
36
|
+
// 已经有桌宠就直接返回路径;没有就下载(同一时间只下一份)
|
|
37
|
+
export function ensurePet(notify = () => {}) {
|
|
38
|
+
if (fs.existsSync(PET_EXE)) return Promise.resolve(PET_EXE)
|
|
39
|
+
running ??= download(notify).finally(() => { running = null })
|
|
40
|
+
return running
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async function download(notify) {
|
|
44
|
+
const work = path.join(PET_HOME, `download-${PET.version}`)
|
|
45
|
+
fs.mkdirSync(work, { recursive: true })
|
|
46
|
+
const zip = path.join(work, 'pet.zip')
|
|
47
|
+
notify(`blue whale:第一次使用,正在下载桌宠(约 ${Math.round(PET.size / 1048576)}MB),下好后会自动出来`)
|
|
48
|
+
log('开始下载桌宠', PET.version)
|
|
49
|
+
|
|
50
|
+
let ok = false
|
|
51
|
+
for (const source of PET.sources) {
|
|
52
|
+
try {
|
|
53
|
+
await fetchSource(source, work, zip)
|
|
54
|
+
if (await sha256(zip) !== PET.sha256) throw new Error('文件指纹对不上(下载不完整或被改过)')
|
|
55
|
+
ok = true
|
|
56
|
+
log(`桌宠从 ${source.name} 下载完成`)
|
|
57
|
+
break
|
|
58
|
+
} catch (e) {
|
|
59
|
+
log(`从 ${source.name} 下载桌宠失败:`, e.message || e)
|
|
60
|
+
fs.rmSync(zip, { force: true })
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
if (!ok) {
|
|
64
|
+
notify('blue whale:桌宠下载失败,请检查网络后重启 DeepSeek Harness 再试;也可以到 Gitee / GitHub 手动下载安装包')
|
|
65
|
+
throw new Error('桌宠下载失败')
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
notify('blue whale:桌宠下载好了,正在解压……')
|
|
69
|
+
const unpack = path.join(work, 'unpack')
|
|
70
|
+
fs.rmSync(unpack, { recursive: true, force: true })
|
|
71
|
+
fs.mkdirSync(unpack, { recursive: true })
|
|
72
|
+
await run(path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'tar.exe'), ['-xf', zip, '-C', unpack])
|
|
73
|
+
const inner = path.join(unpack, PET.inner)
|
|
74
|
+
if (!fs.existsSync(path.join(inner, 'airi.exe'))) throw new Error('解压后找不到 airi.exe(可能被杀毒软件删了)')
|
|
75
|
+
fs.rmSync(PET_DIR, { recursive: true, force: true })
|
|
76
|
+
fs.mkdirSync(PET_DIR, { recursive: true })
|
|
77
|
+
fs.renameSync(inner, path.join(PET_DIR, '桌宠'))
|
|
78
|
+
fs.rmSync(work, { recursive: true, force: true })
|
|
79
|
+
// 旧版本的桌宠用不到了,删掉省空间
|
|
80
|
+
for (const name of fs.readdirSync(PET_HOME)) {
|
|
81
|
+
if (/^pet-/.test(name) && name !== path.basename(PET_DIR)) fs.rmSync(path.join(PET_HOME, name), { recursive: true, force: true })
|
|
82
|
+
}
|
|
83
|
+
log('桌宠已装好:', PET_EXE)
|
|
84
|
+
notify('blue whale:桌宠装好了')
|
|
85
|
+
return PET_EXE
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// 按顺序下每个分卷,接到 zip 后面;已经下完整的分卷(.done 记着大小)不重下
|
|
89
|
+
async function fetchSource(source, work, zip) {
|
|
90
|
+
const files = []
|
|
91
|
+
for (const [i, url] of source.parts.entries()) {
|
|
92
|
+
const file = path.join(work, `${source.name}-${i + 1}.part`)
|
|
93
|
+
const done = file + '.done'
|
|
94
|
+
if (!(fs.existsSync(done) && fs.existsSync(file) && fs.statSync(file).size === Number(fs.readFileSync(done, 'utf8')))) {
|
|
95
|
+
fs.rmSync(done, { force: true })
|
|
96
|
+
await fetchFile(url, file)
|
|
97
|
+
fs.writeFileSync(done, String(fs.statSync(file).size))
|
|
98
|
+
}
|
|
99
|
+
files.push(file)
|
|
100
|
+
log(`${source.name} 第 ${i + 1}/${source.parts.length} 份下好了`)
|
|
101
|
+
}
|
|
102
|
+
fs.rmSync(zip, { force: true })
|
|
103
|
+
for (const file of files) fs.appendFileSync(zip, fs.readFileSync(file))
|
|
104
|
+
if (fs.statSync(zip).size !== PET.size) throw new Error(`大小不对:${fs.statSync(zip).size},应该是 ${PET.size}`)
|
|
105
|
+
for (const file of files) { fs.rmSync(file, { force: true }); fs.rmSync(file + '.done', { force: true }) }
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async function fetchFile(url, file) {
|
|
109
|
+
// 30 秒连不上、或者 60 秒一点数据都没收到,就算这一路失败
|
|
110
|
+
const ctrl = new AbortController()
|
|
111
|
+
let timer = setTimeout(() => ctrl.abort(), 30e3)
|
|
112
|
+
const res = await fetch(url, { signal: ctrl.signal, redirect: 'follow', headers: { 'user-agent': 'dsh-bluewhale' } })
|
|
113
|
+
if (!res.ok || !res.body) throw new Error(`HTTP ${res.status}:${url}`)
|
|
114
|
+
const out = fs.createWriteStream(file)
|
|
115
|
+
try {
|
|
116
|
+
for await (const chunk of res.body) {
|
|
117
|
+
clearTimeout(timer)
|
|
118
|
+
timer = setTimeout(() => ctrl.abort(), 60e3)
|
|
119
|
+
if (!out.write(chunk)) await new Promise((r) => out.once('drain', r))
|
|
120
|
+
}
|
|
121
|
+
} finally {
|
|
122
|
+
clearTimeout(timer)
|
|
123
|
+
await new Promise((r) => out.end(r))
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function sha256(file) {
|
|
128
|
+
return new Promise((resolve, reject) => {
|
|
129
|
+
const hash = crypto.createHash('sha256')
|
|
130
|
+
fs.createReadStream(file).on('data', (d) => hash.update(d)).on('end', () => resolve(hash.digest('hex'))).on('error', reject)
|
|
131
|
+
})
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function run(exe, args) {
|
|
135
|
+
return new Promise((resolve, reject) => {
|
|
136
|
+
execFile(exe, args, { windowsHide: true, maxBuffer: 1 << 24 }, (err, _out, stderr) => (err ? reject(new Error(stderr || err.message)) : resolve()))
|
|
137
|
+
})
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// Windows 右下角弹通知(不用装任何东西);失败就只记日志
|
|
141
|
+
export function toast(text) {
|
|
142
|
+
log(text)
|
|
143
|
+
const xml = `<toast><visual><binding template="ToastGeneric"><text>${text.replace(/[<>&"']/g, (c) => `&#${c.charCodeAt(0)};`)}</text></binding></visual></toast>`
|
|
144
|
+
const script = [
|
|
145
|
+
'[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null',
|
|
146
|
+
'[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null',
|
|
147
|
+
'$x = New-Object Windows.Data.Xml.Dom.XmlDocument',
|
|
148
|
+
`$x.LoadXml('${xml.replace(/'/g, "''")}')`,
|
|
149
|
+
// 借用 PowerShell 的应用 ID,通知才能显示出来
|
|
150
|
+
"[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe').Show([Windows.UI.Notifications.ToastNotification]::new($x))",
|
|
151
|
+
].join('; ')
|
|
152
|
+
execFile('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { windowsHide: true, timeout: 15000 }, () => {})
|
|
153
|
+
}
|
package/src/pet-rules.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// 桌宠说的话交给会话前,加上开头标签(默认 [from the blue whale],不带时间)
|
|
2
|
+
// prompt 模式(默认):标签 + 话 + 插件根目录「桌宠规则.md」的全文,每句都带
|
|
3
|
+
// tag 模式:只带标签 + 话;规则由用户自己贴进角色的记忆 / AGENTS.md
|
|
4
|
+
// 规则文件每次读,改完不用重启 DSH
|
|
5
|
+
import fs from 'node:fs'
|
|
6
|
+
import path from 'node:path'
|
|
7
|
+
import { ROOT } from './state.js'
|
|
8
|
+
|
|
9
|
+
export const RULES_FILE = path.join(ROOT, '桌宠规则.md')
|
|
10
|
+
|
|
11
|
+
export function loadRules() {
|
|
12
|
+
try {
|
|
13
|
+
return fs.readFileSync(RULES_FILE, 'utf8').replace(/^/, '').trim()
|
|
14
|
+
} catch {
|
|
15
|
+
return ''
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function petMessage(speech, cfg) {
|
|
20
|
+
const head = `${cfg.petTag} ${speech}`.trim()
|
|
21
|
+
if (cfg.ruleMode !== 'prompt') return head
|
|
22
|
+
const rules = loadRules()
|
|
23
|
+
return rules ? `${head}\n\n(${rules})` : head
|
|
24
|
+
}
|
package/src/pet.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// 桌宠(AIRI 特别版)跟着 DSH 开关:DSH 启动时打开,DSH 退出时关掉
|
|
2
|
+
// 桌宠已经开着就不重复打开;不是插件打开的桌宠,退出时也不去关
|
|
3
|
+
import fs from 'node:fs'
|
|
4
|
+
import { spawn, execFile } from 'node:child_process'
|
|
5
|
+
import { log } from './state.js'
|
|
6
|
+
|
|
7
|
+
function runPowerShell(script) {
|
|
8
|
+
return new Promise((resolve) => {
|
|
9
|
+
execFile('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { timeout: 10000, windowsHide: true }, (err, stdout) => resolve(err ? '' : stdout))
|
|
10
|
+
})
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
async function isRunning(exe) {
|
|
14
|
+
const out = await runPowerShell(`(Get-Process -Name airi -ErrorAction SilentlyContinue | Where-Object { $_.Path -eq '${exe.replace(/'/g, "''")}' } | Measure-Object).Count`)
|
|
15
|
+
return Number(out.trim()) > 0
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// DSH 的插件运行在「Electron 当 Node 用」的进程里(ELECTRON_RUN_AS_NODE=1)
|
|
19
|
+
// 这些变量传给 airi.exe 的话,它也会当成 Node 启动然后马上退出,所以要去掉
|
|
20
|
+
function cleanEnv() {
|
|
21
|
+
const env = { ...process.env }
|
|
22
|
+
for (const key of Object.keys(env)) {
|
|
23
|
+
if (/^(ELECTRON_|NODE_OPTIONS$|NODE_PATH$|NODE_ENV$|DSH_)/i.test(key)) delete env[key]
|
|
24
|
+
}
|
|
25
|
+
return env
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function createPetLauncher(cfg) {
|
|
29
|
+
let child = null
|
|
30
|
+
|
|
31
|
+
return {
|
|
32
|
+
async start() {
|
|
33
|
+
if (!fs.existsSync(cfg.airiExe)) return log('找不到桌宠程序:', cfg.airiExe)
|
|
34
|
+
if (await isRunning(cfg.airiExe)) return log('桌宠已经开着了')
|
|
35
|
+
child = spawn(cfg.airiExe, [], { detached: true, stdio: 'ignore', windowsHide: false, env: cleanEnv() })
|
|
36
|
+
child.on('error', (e) => log('打开桌宠失败:', e))
|
|
37
|
+
child.unref()
|
|
38
|
+
log('已打开桌宠,进程', child.pid)
|
|
39
|
+
},
|
|
40
|
+
stop() {
|
|
41
|
+
if (!child?.pid || !cfg.closePetOnExit) return
|
|
42
|
+
// /T 连同 AIRI 的子进程一起关
|
|
43
|
+
execFile('taskkill', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true }, () => {})
|
|
44
|
+
log('已关闭桌宠')
|
|
45
|
+
child = null
|
|
46
|
+
},
|
|
47
|
+
}
|
|
48
|
+
}
|
package/src/route.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// 分拣 AIRI 发来的请求:AIRI 说一句话会发好几个请求,只有真正的聊天请求才交给 DSH
|
|
2
|
+
// 聊天请求:最后一条 user 消息像 "[2026-10-25 13:49] 我说今天挺想你的。\n[Context]\n- system:..."
|
|
3
|
+
// 辅助请求:user 内容是 JSON,如 {"previousMessages":[],"transcript":"..."} 或 ["..."](判断说完没有、修正识别结果)
|
|
4
|
+
|
|
5
|
+
const TIMESTAMP = /^\s*\[\d{4}-\d{1,2}-\d{1,2}[ T]\d{1,2}:\d{2}(:\d{2})?\]\s*/
|
|
6
|
+
const CONTEXT = /(^|\n)\s*\[Context\]/
|
|
7
|
+
|
|
8
|
+
// 取最后一条 user 消息的文字;历史和 system 提示词都忽略
|
|
9
|
+
export function lastUserText(body) {
|
|
10
|
+
const msg = (body?.messages || []).filter((m) => m.role === 'user').at(-1)
|
|
11
|
+
if (!msg) return ''
|
|
12
|
+
if (typeof msg.content === 'string') return msg.content.trim()
|
|
13
|
+
if (Array.isArray(msg.content)) {
|
|
14
|
+
return msg.content.filter((p) => p.type === 'text').map((p) => p.text).join('\n').trim()
|
|
15
|
+
}
|
|
16
|
+
return ''
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function looksLikeJson(text) {
|
|
20
|
+
if (!/^[[{]/.test(text)) return false
|
|
21
|
+
try {
|
|
22
|
+
JSON.parse(text)
|
|
23
|
+
return true
|
|
24
|
+
} catch {
|
|
25
|
+
return false
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// 是不是真正的聊天请求:开头有 [时间戳],或者带 [Context] 段;内容是 JSON 的一律算辅助请求
|
|
30
|
+
export function isChatRequest(body) {
|
|
31
|
+
const text = lastUserText(body)
|
|
32
|
+
if (!text || looksLikeJson(text)) return false
|
|
33
|
+
return TIMESTAMP.test(text) || CONTEXT.test(text)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// 只留下真正说的话:删掉 [Context] 及之后的全部内容,再去掉开头的 [时间戳]
|
|
37
|
+
// 角色靠插件加的开头标签(pet-rules.js)认出这是桌宠消息,不再靠时间戳
|
|
38
|
+
export function extractSpeech(text) {
|
|
39
|
+
return String(text ?? '')
|
|
40
|
+
.split(CONTEXT)[0]
|
|
41
|
+
.replace(TIMESTAMP, '')
|
|
42
|
+
.trim()
|
|
43
|
+
}
|
package/src/server.js
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
// 给 AIRI 用的 OpenAI 兼容接口(AIRI 的意识模块填 http://127.0.0.1:端口/v1/)
|
|
2
|
+
// GET /v1/models → 一个模型 "dsh"
|
|
3
|
+
// POST /v1/chat/completions → 支持普通 JSON 和 stream: true(SSE)
|
|
4
|
+
// 桌宠托盘「切换聊天」用:
|
|
5
|
+
// GET /dafei/sessions → { current, sessions: [{ id, title, active }] }
|
|
6
|
+
// POST /dafei/session → { id } 切到那个会话;{ new: true } 下一句话新建会话
|
|
7
|
+
import http from 'node:http'
|
|
8
|
+
import { randomUUID } from 'node:crypto'
|
|
9
|
+
import { ask } from './dsh.js'
|
|
10
|
+
import { listSessions } from './sessions.js'
|
|
11
|
+
import { loadState, saveState, log } from './state.js'
|
|
12
|
+
import { cleanForSpeech, splitSentences } from './clean-text.js'
|
|
13
|
+
import { isChatRequest, lastUserText, extractSpeech } from './route.js'
|
|
14
|
+
import { withIdleMotion } from './idle-motion.js'
|
|
15
|
+
import { withOutfitMotions } from './outfit.js'
|
|
16
|
+
import { localHelperReply, forwardToDeepSeek } from './helpers.js'
|
|
17
|
+
import { isVisionRequest, describeImages } from './vision.js'
|
|
18
|
+
import { createFollowups, PENDING_MARK } from './followups.js'
|
|
19
|
+
import { petMessage } from './pet-rules.js'
|
|
20
|
+
|
|
21
|
+
const MODEL = 'dsh'
|
|
22
|
+
// aurabot 等插件让角色「不说话」时写的标记
|
|
23
|
+
const SILENCE = /^\s*[[[((]沉默[\]]))]\s*$/
|
|
24
|
+
|
|
25
|
+
export function createServer(ctx, cfg) {
|
|
26
|
+
// 角色的原始回复 → 桌宠念的文字(带动作标记);`|||` 是 aurabot 分条的写法,当成一句结束
|
|
27
|
+
function speakable(raw) {
|
|
28
|
+
if (!raw || SILENCE.test(raw)) return ''
|
|
29
|
+
const spoken = withOutfitMotions(cleanForSpeech(String(raw).replace(/\s*\|\|\|\s*/g, '。\n')), cfg.outfitMotions)
|
|
30
|
+
return withIdleMotion(spoken, cfg.idleMotions)
|
|
31
|
+
}
|
|
32
|
+
const followups = createFollowups(ctx, { prepare: speakable })
|
|
33
|
+
|
|
34
|
+
// 同一时间只让角色处理一句话,后来的排队
|
|
35
|
+
let queue = Promise.resolve()
|
|
36
|
+
const enqueue = (task) => {
|
|
37
|
+
const result = queue.then(task, task)
|
|
38
|
+
queue = result.catch(() => {})
|
|
39
|
+
return result
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async function chatReply(text) {
|
|
43
|
+
if (!text) return cfg.fallbackReply
|
|
44
|
+
const started = Date.now()
|
|
45
|
+
log('← 收到:' + text)
|
|
46
|
+
followups.open()
|
|
47
|
+
try {
|
|
48
|
+
const reply = speakable(await enqueue(() => ask(ctx, cfg, petMessage(text, cfg))))
|
|
49
|
+
followups.forget(reply)
|
|
50
|
+
log(`→ 回复(${((Date.now() - started) / 1000).toFixed(1)}s):${reply}`)
|
|
51
|
+
return reply || cfg.fallbackReply
|
|
52
|
+
} catch (e) {
|
|
53
|
+
// 报错只写日志,不返回给 AIRI
|
|
54
|
+
log(`✗ 出错:[${e.code || 'ERROR'}]`, e)
|
|
55
|
+
return cfg.fallbackReply
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function visionReply(body) {
|
|
60
|
+
const started = Date.now()
|
|
61
|
+
try {
|
|
62
|
+
const text = await describeImages(ctx, cfg, body)
|
|
63
|
+
log(`👁 看图(${((Date.now() - started) / 1000).toFixed(1)}s):${text.slice(0, 80)}`)
|
|
64
|
+
return text
|
|
65
|
+
} catch (e) {
|
|
66
|
+
log('✗ 看图出错:', e)
|
|
67
|
+
return ''
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async function helperReply(body) {
|
|
72
|
+
const text = lastUserText(body)
|
|
73
|
+
if (cfg.helperMode === 'deepseek' && cfg.deepseekApiKey) {
|
|
74
|
+
try {
|
|
75
|
+
return await forwardToDeepSeek(body, cfg)
|
|
76
|
+
} catch (e) {
|
|
77
|
+
log('✗ 辅助请求转发失败,改为本地回答:', e.message)
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return localHelperReply(body, text)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async function chatCompletions(req, res) {
|
|
84
|
+
let body
|
|
85
|
+
try {
|
|
86
|
+
const raw = await readText(req)
|
|
87
|
+
body = raw ? JSON.parse(raw) : {}
|
|
88
|
+
} catch {
|
|
89
|
+
return sendJson(res, 400, { error: { message: 'Invalid JSON body', type: 'invalid_request_error' } })
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// 桌宠来取后续消息(通知请求,内容含 PENDING_MARK):直接交出存着的话,不发给角色
|
|
93
|
+
const pendingRequest = lastUserText(body).includes(PENDING_MARK)
|
|
94
|
+
if (pendingRequest) log(`⤷ 桌宠取走后续消息(${followups.count()} 条)`)
|
|
95
|
+
const reply = pendingRequest
|
|
96
|
+
? followups.take()
|
|
97
|
+
: isVisionRequest(body)
|
|
98
|
+
? await visionReply(body)
|
|
99
|
+
: isChatRequest(body)
|
|
100
|
+
? await chatReply(extractSpeech(lastUserText(body)))
|
|
101
|
+
: await helperReply(body)
|
|
102
|
+
const id = 'chatcmpl-' + randomUUID()
|
|
103
|
+
const created = Math.floor(Date.now() / 1000)
|
|
104
|
+
|
|
105
|
+
if (!body.stream) {
|
|
106
|
+
return sendJson(res, 200, {
|
|
107
|
+
id,
|
|
108
|
+
object: 'chat.completion',
|
|
109
|
+
created,
|
|
110
|
+
model: MODEL,
|
|
111
|
+
choices: [{ index: 0, message: { role: 'assistant', content: reply }, finish_reason: 'stop' }],
|
|
112
|
+
usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },
|
|
113
|
+
})
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// 流式:角色一整轮说完才有回复,所以一句一句发出去
|
|
117
|
+
if (res.destroyed) return
|
|
118
|
+
res.writeHead(200, { 'Content-Type': 'text/event-stream; charset=utf-8', 'Cache-Control': 'no-cache', Connection: 'keep-alive' })
|
|
119
|
+
const chunk = (delta, finish = null) =>
|
|
120
|
+
`data: ${JSON.stringify({ id, object: 'chat.completion.chunk', created, model: MODEL, choices: [{ index: 0, delta, finish_reason: finish }] })}\n\n`
|
|
121
|
+
res.write(chunk({ role: 'assistant', content: '' }))
|
|
122
|
+
for (const sentence of splitSentences(reply)) res.write(chunk({ content: sentence }))
|
|
123
|
+
res.write(chunk({}, 'stop'))
|
|
124
|
+
res.end('data: [DONE]\n\n')
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function switchSession(req, res) {
|
|
128
|
+
let body = {}
|
|
129
|
+
try {
|
|
130
|
+
body = JSON.parse((await readText(req)) || '{}')
|
|
131
|
+
} catch {}
|
|
132
|
+
if (body.new) {
|
|
133
|
+
saveState({ sessionId: null })
|
|
134
|
+
return sendJson(res, 200, { ok: true, current: null })
|
|
135
|
+
}
|
|
136
|
+
const s = listSessions(cfg.workDir, cfg.allWorkspaces).find((x) => x.id === body.id)
|
|
137
|
+
if (!s) return sendJson(res, 404, { ok: false, error: `找不到会话 ${body.id}` })
|
|
138
|
+
saveState({ sessionId: s.id })
|
|
139
|
+
log(`切换会话:${s.title}`)
|
|
140
|
+
return sendJson(res, 200, { ok: true, current: s.id })
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const server = http.createServer(async (req, res) => {
|
|
144
|
+
res.setHeader('Access-Control-Allow-Origin', '*')
|
|
145
|
+
res.setHeader('Access-Control-Allow-Headers', '*')
|
|
146
|
+
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
|
|
147
|
+
if (req.method === 'OPTIONS') return res.writeHead(204).end()
|
|
148
|
+
|
|
149
|
+
// 兼容 /v1/models、/v1//models、/models 等写法
|
|
150
|
+
const path = new URL(req.url, 'http://x').pathname.replace(/\/+/g, '/').replace(/\/$/, '')
|
|
151
|
+
const api = path.replace(/^\/v1/, '')
|
|
152
|
+
try {
|
|
153
|
+
if (req.method === 'GET' && api === '/models') {
|
|
154
|
+
return sendJson(res, 200, { object: 'list', data: [{ id: MODEL, object: 'model', created: 0, owned_by: 'dsh-dafei' }] })
|
|
155
|
+
}
|
|
156
|
+
if (req.method === 'POST' && api === '/chat/completions') return await chatCompletions(req, res)
|
|
157
|
+
if (req.method === 'GET' && path === '/dafei/sessions') {
|
|
158
|
+
return sendJson(res, 200, { current: loadState().sessionId || null, sessions: listSessions(cfg.workDir, cfg.allWorkspaces) })
|
|
159
|
+
}
|
|
160
|
+
if (req.method === 'POST' && path === '/dafei/session') return await switchSession(req, res)
|
|
161
|
+
if (req.method === 'GET' && path === '/dafei/pending') return sendJson(res, 200, { count: followups.count() })
|
|
162
|
+
if (req.method === 'GET' && path === '/dafei/health') return sendJson(res, 200, { ok: true })
|
|
163
|
+
sendJson(res, 404, { error: { message: `Not found: ${req.method} ${req.url}`, type: 'invalid_request_error' } })
|
|
164
|
+
} catch (e) {
|
|
165
|
+
log('✗ 处理请求出错:', e)
|
|
166
|
+
if (!res.headersSent) sendJson(res, 500, { error: { message: 'internal error', type: 'server_error' } })
|
|
167
|
+
else res.end()
|
|
168
|
+
}
|
|
169
|
+
})
|
|
170
|
+
|
|
171
|
+
// 端口被占(比如旧特别版的桥还开着)就每 10 秒再试一次
|
|
172
|
+
let retryTimer = null
|
|
173
|
+
let closed = false
|
|
174
|
+
const listen = () => server.listen(cfg.port, '127.0.0.1')
|
|
175
|
+
server.on('listening', () => log(`角色接口已启动:http://127.0.0.1:${cfg.port}/v1`))
|
|
176
|
+
server.on('error', (e) => {
|
|
177
|
+
if (e.code !== 'EADDRINUSE' || closed) return log('✗ 接口出错:', e)
|
|
178
|
+
log(`端口 ${cfg.port} 被占用了,10 秒后再试(是不是旧的 dsh-bridge 还开着?)`)
|
|
179
|
+
retryTimer = setTimeout(listen, 10000)
|
|
180
|
+
})
|
|
181
|
+
|
|
182
|
+
return {
|
|
183
|
+
start: listen,
|
|
184
|
+
stop() {
|
|
185
|
+
closed = true
|
|
186
|
+
followups.dispose()
|
|
187
|
+
clearTimeout(retryTimer)
|
|
188
|
+
server.closeAllConnections?.()
|
|
189
|
+
return new Promise((r) => server.close(() => r()))
|
|
190
|
+
},
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function readText(req) {
|
|
195
|
+
return new Promise((resolve, reject) => {
|
|
196
|
+
let data = ''
|
|
197
|
+
req.setEncoding('utf8')
|
|
198
|
+
req.on('data', (c) => (data += c))
|
|
199
|
+
req.on('end', () => resolve(data))
|
|
200
|
+
req.on('error', reject)
|
|
201
|
+
})
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function sendJson(res, status, obj) {
|
|
205
|
+
res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' })
|
|
206
|
+
res.end(JSON.stringify(obj))
|
|
207
|
+
}
|
package/src/sessions.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// 列出会话,给桌宠右键菜单「切换聊天」用
|
|
2
|
+
// 只读 DSH 自己的存储文件,不打开会话,所以很快
|
|
3
|
+
import fs from 'node:fs'
|
|
4
|
+
import os from 'node:os'
|
|
5
|
+
import path from 'node:path'
|
|
6
|
+
|
|
7
|
+
const STORAGE = path.join(os.homedir(), '.dsh', 'storages')
|
|
8
|
+
const CACHE_DIR = path.join(STORAGE, 'session_projcache', 'sessions')
|
|
9
|
+
|
|
10
|
+
const same = (a, b) => path.resolve(a).toLowerCase() === path.resolve(b).toLowerCase()
|
|
11
|
+
|
|
12
|
+
function readWorkspaces() {
|
|
13
|
+
try {
|
|
14
|
+
return JSON.parse(fs.readFileSync(path.join(STORAGE, 'workspace.json'), 'utf8'))
|
|
15
|
+
} catch {
|
|
16
|
+
return {}
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// workDir 对应 App 里的哪个工作区(分组)
|
|
21
|
+
export function findWorkspaceId(workDir) {
|
|
22
|
+
const { tables } = readWorkspaces()
|
|
23
|
+
return Object.entries(tables?.workspaces || {}).find(([, w]) => same(w.path, workDir))?.[0]
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// 菜单最多列这么多个(最近用过的)
|
|
27
|
+
const MAX_SESSIONS = 30
|
|
28
|
+
|
|
29
|
+
// 最近用过的在前:[{ id, title, active }]
|
|
30
|
+
// allWorkspaces = true:所有工作区的会话都列出来,标题前加工作区名(比如「Aurabot · QQ · 和主人的私聊」),
|
|
31
|
+
// 这样能切到别的插件(aurabot 等)建的会话,用它们自己的人设和记忆;false:只列 workDir 里的
|
|
32
|
+
export function listSessions(workDir, allWorkspaces = true) {
|
|
33
|
+
const ws = readWorkspaces()
|
|
34
|
+
const archived = new Set(ws.global?.archivedSessionIds || [])
|
|
35
|
+
const spaces = Object.values(ws.tables?.workspaces || {})
|
|
36
|
+
const spaceName = (cwd) => spaces.find((w) => w.path && same(w.path, cwd))?.title || path.basename(cwd)
|
|
37
|
+
const sessions = []
|
|
38
|
+
for (const f of fs.existsSync(CACHE_DIR) ? fs.readdirSync(CACHE_DIR) : []) {
|
|
39
|
+
const file = path.join(CACHE_DIR, f)
|
|
40
|
+
try {
|
|
41
|
+
const { record } = JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
42
|
+
const id = f.replace(/\.json$/, '')
|
|
43
|
+
const cwd = record.identity.cwd
|
|
44
|
+
if (archived.has(id) || (!allWorkspaces && !same(cwd, workDir))) continue
|
|
45
|
+
const title = String(record.rows.title?.val || record.rows.titleInput?.val?.first?.text || '(无标题)').slice(0, 30)
|
|
46
|
+
sessions.push({ id, title: allWorkspaces ? `${spaceName(cwd)} · ${title}` : title, active: fs.statSync(file).mtime.getTime() })
|
|
47
|
+
} catch {}
|
|
48
|
+
}
|
|
49
|
+
return sessions.sort((a, b) => b.active - a.active).slice(0, MAX_SESSIONS)
|
|
50
|
+
}
|
package/src/state.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import os from 'node:os'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
import { fileURLToPath } from 'node:url'
|
|
5
|
+
|
|
6
|
+
// 插件根目录(src 的上一级)
|
|
7
|
+
export const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
|
8
|
+
|
|
9
|
+
// 状态和日志放哪:从 DSH 插件市场(npm)装的插件住在 node_modules 里,更新时会被整个换掉,所以放到 ~/.dsh/blue-whale/data;手动放的文件夹照旧用插件里的 data\
|
|
10
|
+
export const DATA_DIR = ROOT.split(path.sep).includes('node_modules') ? path.join(os.homedir(), '.dsh', 'blue-whale', 'data') : path.join(ROOT, 'data')
|
|
11
|
+
|
|
12
|
+
// 运行时状态:{ sessionId },桌宠说的话发到哪个会话;重启后继续用同一个
|
|
13
|
+
const STATE_PATH = path.join(DATA_DIR, 'state.json')
|
|
14
|
+
|
|
15
|
+
export function loadState() {
|
|
16
|
+
try {
|
|
17
|
+
// 去掉 BOM,否则 JSON.parse 会报错
|
|
18
|
+
return JSON.parse(fs.readFileSync(STATE_PATH, 'utf8').replace(/^/, ''))
|
|
19
|
+
} catch {
|
|
20
|
+
return {}
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function saveState(patch) {
|
|
25
|
+
const next = { ...loadState(), ...patch }
|
|
26
|
+
fs.mkdirSync(path.dirname(STATE_PATH), { recursive: true })
|
|
27
|
+
// 先写临时文件再改名,避免写到一半断电把文件写坏
|
|
28
|
+
const tmp = STATE_PATH + '.tmp'
|
|
29
|
+
fs.writeFileSync(tmp, JSON.stringify(next, null, 2))
|
|
30
|
+
fs.renameSync(tmp, STATE_PATH)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// 简单日志:写进 data/dafei.log,超过 1MB 就从头写
|
|
34
|
+
const LOG_PATH = path.join(DATA_DIR, 'dafei.log')
|
|
35
|
+
|
|
36
|
+
export function log(...args) {
|
|
37
|
+
const line = `[${new Date().toLocaleString()}] ${args.map((a) => (a instanceof Error ? a.stack || a.message : typeof a === 'string' ? a : JSON.stringify(a))).join(' ')}\n`
|
|
38
|
+
try {
|
|
39
|
+
fs.mkdirSync(path.dirname(LOG_PATH), { recursive: true })
|
|
40
|
+
if (fs.existsSync(LOG_PATH) && fs.statSync(LOG_PATH).size > 1024 * 1024) fs.writeFileSync(LOG_PATH, '')
|
|
41
|
+
fs.appendFileSync(LOG_PATH, line)
|
|
42
|
+
} catch {}
|
|
43
|
+
}
|