dsh-folia 4.26.0-pre.21 → 4.26.0-pre.23
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/client.js +23 -1
- package/lib/routes/pet-chat.js +1207 -1207
- package/lib/voice/record.js +15 -2
- package/package.json +1 -1
package/lib/routes/pet-chat.js
CHANGED
|
@@ -1,1208 +1,1208 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* routes/pet-chat.js — **桌宠对话**路由族:`/pet-chat/*`(门 2 / 任务 A2)。
|
|
3
|
-
*
|
|
4
|
-
* 四条端点(契约见插件仓库 docs/PET-CHAT-PLAN.md §2.2):
|
|
5
|
-
* GET /folia/pet-chat/state → { enabled, provider, model, reachable, lastError }
|
|
6
|
-
* GET /folia/pet-chat/models → ollama 的 /api/tags 列表(openai 返回空 + hint)
|
|
7
|
-
* POST /folia/pet-chat/chat → SSE:event: delta {"t"} / done {usage,emotion} / error {code,hint}
|
|
8
|
-
* POST /folia/pet-chat/reset → 清空会话记忆
|
|
9
|
-
*
|
|
10
|
-
* 纪律(工单 §2.2 的约束,逐条对上):
|
|
11
|
-
* · **只转发到用户配置的端点**:baseUrl 来自设置(空 = 该 provider 的默认端点),
|
|
12
|
-
* 不接受请求体里带 URL —— 否则这个路由会变成任意转发器。
|
|
13
|
-
* · **超时 20s**:AbortController;到点即发 `error{code:'timeout'}` 并断流。
|
|
14
|
-
* · **限频 1 次/秒**(同一来源 IP):超了直接 `error{code:'rate-limited'}`,不再打模型。
|
|
15
|
-
* · **输入 ≤400 字**:超长 `error{code:'bad-request'}`(客户端也会截断,这里是服务端兜底)。
|
|
16
|
-
* · **key 不进日志**:本文件**一行都不打印** apiKey / 请求头;错误文案只带状态码。
|
|
17
|
-
* · 会话记忆在**宿主进程内存**里(reset 清空),不落盘:重启即忘,符合"只在本次会话里聊"。
|
|
18
|
-
*
|
|
19
|
-
* 依赖面(与 test/verify-inject-contracts.mjs 双向对账):`disposers` / `base` / `log` / `readSettings`。
|
|
20
|
-
*/
|
|
21
|
-
|
|
22
|
-
/** 注入契约:本族从 `c` 消费的**必需**键(门面/注册表调用点必须逐键给到)。 */
|
|
23
|
-
// `speechToText`:DSH 宿主的转写服务(`ctx.speechToText`)。它可能**不存在**(用户没启用
|
|
24
|
-
// 「语音输入」实验特性)—— 那种情况由路由回 `asr-not-ready`,而不是启动失败。
|
|
25
|
-
export const DEPS = ['disposers', 'base', 'log', 'readSettings', 'speechToText'];
|
|
26
|
-
|
|
27
|
-
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
|
28
|
-
import { homedir, tmpdir } from 'node:os';
|
|
29
|
-
import { dirname, join } from 'node:path';
|
|
30
|
-
|
|
31
|
-
import {
|
|
32
|
-
readMemory, writeMemory, clearMemory, parseExplicitMemory, rememberExplicit,
|
|
33
|
-
mergeSummary, memoryPromptLine, MEMORY_SUMMARY_PROMPT,
|
|
34
|
-
} from '../pet-chat-memory.js';
|
|
35
|
-
// v0.1:旧键迁移与默认值只在 settings-schema 定义一次,路由复用同一个函数
|
|
36
|
-
import { readPetChat as normalizePetChat } from '../settings-schema.js';
|
|
37
|
-
import { createVoiceRecorder, defaultResolveFfmpeg, defaultRunFfmpeg } from '../voice/record.js';
|
|
38
|
-
// 本地 STT:资源不下发到 npm 包,首次使用时从站点 R2 下载(见 lib/asr/asr-local.js)
|
|
39
|
-
import { ensureInstalled as ensureAsrInstalled, startWorker as startAsrWorker } from '../asr/asr-local.js';
|
|
40
|
-
// v0.1「零配置」主动搭话:固定策略 + 语音指令静默(追加决定 1/2)
|
|
41
|
-
import {
|
|
42
|
-
canSpeak, markSaid, buildProactiveLine, readProactiveState, todayUsage, isSilent,
|
|
43
|
-
enterSilence, clearSilence, parseSilenceCommand, PROACTIVE_RULES,
|
|
44
|
-
} from '../pet-chat-proactive.js';
|
|
45
|
-
|
|
46
|
-
/** 单次输入上限(工单:≤400 字)。 */
|
|
47
|
-
const MAX_INPUT_CHARS = 400;
|
|
48
|
-
/** 模型调用超时(工单:20s)。 */
|
|
49
|
-
const TIMEOUT_MS = 20000;
|
|
50
|
-
/** 同一来源的最小间隔(工单:1 次/秒)。 */
|
|
51
|
-
const RATE_LIMIT_MS = 1000;
|
|
52
|
-
/** 会话记忆最多保留的轮数(一轮 = 一问一答)。 */
|
|
53
|
-
const MAX_MEMORY_TURNS = 12;
|
|
54
|
-
|
|
55
|
-
/**
|
|
56
|
-
* 上下文轮数 / 单条字数上限(v0.1 起不再暴露给用户)。
|
|
57
|
-
*
|
|
58
|
-
* 为什么从设置里拿掉:工单 §4「解耦」与 §5「默认值只在 settings-schema 定义一次」——
|
|
59
|
-
* 这两项属于实现细节,用户只需要"填 key、选音色、起名字"。留在设置里只会让
|
|
60
|
-
* 配置面板变成一长串旋钮(旧版本正是因为这点被推翻的)。
|
|
61
|
-
*/
|
|
62
|
-
const DEFAULT_MAX_TURNS = 8;
|
|
63
|
-
const DEFAULT_MAX_CHARS = 80;
|
|
64
|
-
/** 每 N 轮写一次记忆摘要。 */
|
|
65
|
-
const DEFAULT_MEMORY_EVERY_TURNS = 10;
|
|
66
|
-
|
|
67
|
-
/* ── 语音转写(PET-CHAT-ROUND-NEXT 之后的一轮)────────────────────────────── */
|
|
68
|
-
/** 单段音频上限:15 秒(16kHz 单声道 PCM16 ≈ 480KB)。 */
|
|
69
|
-
const ASR_MAX_SECONDS = 15;
|
|
70
|
-
/** 单段音频字节上限:2MB(工单 B 的硬约束)。 */
|
|
71
|
-
const ASR_MAX_BYTES = 2 * 1024 * 1024;
|
|
72
|
-
/** 同一来源的转写最小间隔:1 次 / 2 秒。 */
|
|
73
|
-
const ASR_RATE_LIMIT_MS = 2000;
|
|
74
|
-
/** 转写超时:模型推理可能要几秒,给 20s。 */
|
|
75
|
-
const ASR_TIMEOUT_MS = 20000;
|
|
76
|
-
/** DSH 语音输入 bundle 注册的本地 provider id(契约见 docs/ASR-INTEGRATION.md)。 */
|
|
77
|
-
const ASR_PROVIDER_ID = 'sensevoice-local';
|
|
78
|
-
/** 转写语言(本功能只做中文;要别的语种先改契约)。 */
|
|
79
|
-
const ASR_LANGUAGE = 'zh';
|
|
80
|
-
/** 未就绪时给用户的一句话(两条路径共用,避免文案漂移)。 */
|
|
81
|
-
const ASR_NOT_READY_HINT = '语音输入还没就绪:模型还没下载好,稍等一下';
|
|
82
|
-
|
|
83
|
-
/* ── 本地 STT 运行时(自带 SenseVoice,不依赖 DSH 的语音实验包)─────────────── */
|
|
84
|
-
/**
|
|
85
|
-
* 安装根:`~/.dsh-folia/asr/v1`。
|
|
86
|
-
* 首次点桌宠说话时从站点下载(约 340MB;node.exe 复用 tts 包),之后完全离线。
|
|
87
|
-
*/
|
|
88
|
-
const ASR_ROOT = process.env.FOLIA_ASR_ROOT || join(homedir(), '.dsh-folia', 'asr', 'v1');
|
|
89
|
-
/** 下载/就绪状态(GET /pet-chat/asr 直接回它)。 */
|
|
90
|
-
let asrState = { phase: 'idle', doneBytes: 0, totalBytes: 0, error: null };
|
|
91
|
-
/** worker 实例(懒启动,常驻)。 */
|
|
92
|
-
let asrWorker = null;
|
|
93
|
-
/** 正在进行的安装任务(并发点击 join 同一个 Promise)。 */
|
|
94
|
-
let asrInstallPromise = null;
|
|
95
|
-
|
|
96
|
-
/** 本地运行时是否已经装在盘上(不下载、只探测)。 */
|
|
97
|
-
function asrInstalledOnDisk() {
|
|
98
|
-
try {
|
|
99
|
-
return existsSync(join(ASR_ROOT, 'runtime', 'asr-worker.cjs'))
|
|
100
|
-
&& existsSync(join(ASR_ROOT, 'runtime', 'node.exe'))
|
|
101
|
-
&& existsSync(join(ASR_ROOT, 'models', 'sensevoice', 'tokens.txt'));
|
|
102
|
-
} catch { return false; }
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
/**
|
|
106
|
-
* 确保本地 STT 可用:装包 → 启 worker。返回 worker;失败抛错并记 asrState.failed。
|
|
107
|
-
* 幂等:并发调用共享同一个安装 Promise。
|
|
108
|
-
*/
|
|
109
|
-
function ensureLocalAsr() {
|
|
110
|
-
if (asrWorker) return Promise.resolve(asrWorker);
|
|
111
|
-
if (asrInstallPromise) return asrInstallPromise;
|
|
112
|
-
asrInstallPromise = (async () => {
|
|
113
|
-
if (!asrInstalledOnDisk()) {
|
|
114
|
-
asrState = { phase: 'downloading', doneBytes: 0, totalBytes: 0, error: null };
|
|
115
|
-
await ensureAsrInstalled(ASR_ROOT, {
|
|
116
|
-
onProgress: (p) => {
|
|
117
|
-
asrState = {
|
|
118
|
-
phase: 'downloading',
|
|
119
|
-
doneBytes: Number(p.doneBytes) || 0,
|
|
120
|
-
totalBytes: Number(p.totalBytes) || 0,
|
|
121
|
-
error: null,
|
|
122
|
-
};
|
|
123
|
-
},
|
|
124
|
-
});
|
|
125
|
-
}
|
|
126
|
-
asrState = { phase: 'loading', doneBytes: asrState.doneBytes, totalBytes: asrState.totalBytes, error: null };
|
|
127
|
-
asrWorker = startAsrWorker(ASR_ROOT);
|
|
128
|
-
asrState = { phase: 'ready', doneBytes: asrState.doneBytes, totalBytes: asrState.totalBytes, error: null };
|
|
129
|
-
return asrWorker;
|
|
130
|
-
})().catch((error) => {
|
|
131
|
-
asrWorker = null;
|
|
132
|
-
asrState = {
|
|
133
|
-
phase: 'failed',
|
|
134
|
-
doneBytes: asrState.doneBytes,
|
|
135
|
-
totalBytes: asrState.totalBytes,
|
|
136
|
-
error: String((error && error.message) || error),
|
|
137
|
-
};
|
|
138
|
-
asrInstallPromise = null;
|
|
139
|
-
throw error;
|
|
140
|
-
});
|
|
141
|
-
return asrInstallPromise;
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
/** 本地 STT 是否已就绪(已装或已启动)—— 决定 /transcribe 走本地还是 DSH 服务。 */
|
|
145
|
-
async function localAsrReady() {
|
|
146
|
-
if (asrWorker) return true;
|
|
147
|
-
return asrInstalledOnDisk();
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
/**
|
|
151
|
-
* 解析 16kHz 单声道 PCM16 WAV 的时长(秒)。
|
|
152
|
-
*
|
|
153
|
-
* 为什么自己解析而不是看 `content-length`:15 秒的上限是**时长**约束,
|
|
154
|
-
* 而 44.1kHz 立体声的 15 秒会是 2.6MB —— 只看字节数会把合法的短音频挡掉。
|
|
155
|
-
* 只认 `RIFF/WAVE` + `fmt ` + `data` 三块;不是 WAV 就返回 null(调用方回 400)。
|
|
156
|
-
*/
|
|
157
|
-
export function wavSeconds(bytes) {
|
|
158
|
-
if (!bytes || bytes.byteLength < 44) return null;
|
|
159
|
-
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
160
|
-
const tag = (offset) => String.fromCharCode(bytes[offset], bytes[offset + 1], bytes[offset + 2], bytes[offset + 3]);
|
|
161
|
-
if (tag(0) !== 'RIFF' || tag(8) !== 'WAVE') return null;
|
|
162
|
-
let offset = 12;
|
|
163
|
-
let sampleRate = 0;
|
|
164
|
-
let channels = 0;
|
|
165
|
-
let bits = 0;
|
|
166
|
-
let dataBytes = 0;
|
|
167
|
-
while (offset + 8 <= bytes.byteLength) {
|
|
168
|
-
const id = tag(offset);
|
|
169
|
-
const size = view.getUint32(offset + 4, true);
|
|
170
|
-
const body = offset + 8;
|
|
171
|
-
if (id === 'fmt ' && body + 16 <= bytes.byteLength) {
|
|
172
|
-
channels = view.getUint16(body + 2, true);
|
|
173
|
-
sampleRate = view.getUint32(body + 4, true);
|
|
174
|
-
bits = view.getUint16(body + 14, true);
|
|
175
|
-
} else if (id === 'data') {
|
|
176
|
-
dataBytes = Math.min(size, bytes.byteLength - body);
|
|
177
|
-
break;
|
|
178
|
-
}
|
|
179
|
-
offset = body + size + (size % 2);
|
|
180
|
-
if (size <= 0) break;
|
|
181
|
-
}
|
|
182
|
-
if (!sampleRate || !channels || !bits || !dataBytes) return null;
|
|
183
|
-
const bytesPerFrame = channels * (bits / 8);
|
|
184
|
-
if (!bytesPerFrame) return null;
|
|
185
|
-
const seconds = dataBytes / (sampleRate * bytesPerFrame);
|
|
186
|
-
return Number.isFinite(seconds) ? seconds : null;
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
/** base64 → Uint8Array(浏览器与 Node 都能用;Node 走 Buffer 分支)。 */
|
|
190
|
-
export function decodeBase64(text) {
|
|
191
|
-
const clean = String(text || '');
|
|
192
|
-
if (!clean) return new Uint8Array(0);
|
|
193
|
-
if (typeof Buffer !== 'undefined') return new Uint8Array(Buffer.from(clean, 'base64'));
|
|
194
|
-
const binary = atob(clean);
|
|
195
|
-
const bytes = new Uint8Array(binary.length);
|
|
196
|
-
for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
|
|
197
|
-
return bytes;
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
/** 各 provider 的默认端点 / 默认模型(设置里 baseUrl / model 为空时用)。 */
|
|
201
|
-
const PROVIDER_DEFAULTS = {
|
|
202
|
-
// Ollama 的 OpenAI 兼容前缀是 /v1(少了它 /chat/completions 会 404)
|
|
203
|
-
ollama: { baseUrl: 'http://127.0.0.1:11434/v1', model: 'qwen2.5:7b' },
|
|
204
|
-
openai: { baseUrl: 'https://api.deepseek.com', model: 'deepseek-chat' },
|
|
205
|
-
};
|
|
206
|
-
|
|
207
|
-
const EMO_CODES = Object.freeze(['happy', 'calm', 'tired', 'angry']);
|
|
208
|
-
|
|
209
|
-
/** 情绪关键词兜底(模型没给合法 emotion 时用;与客户端预设台词同一套分组)。 */
|
|
210
|
-
const EMO_KEYWORDS = [
|
|
211
|
-
['happy', /哈哈|好耶|开心|太好了|喜欢|嘿嘿|✧|(^|^_^|😊|🎉/u],
|
|
212
|
-
['tired', /困|累|睡|休息|晚安|疲惫|zzz/i],
|
|
213
|
-
['angry', /生气|讨厌|烦|哼|气死|😠/u],
|
|
214
|
-
['calm', /算了|不知道|还好|一般|平静|嗯/],
|
|
215
|
-
];
|
|
216
|
-
|
|
217
|
-
/**
|
|
218
|
-
* 从一段文本里取 `{reply, emotion}`。
|
|
219
|
-
*
|
|
220
|
-
* 模型被要求输出 `{"reply":"...","emotion":"happy|calm|tired|angry"}`;
|
|
221
|
-
* 不是合法 JSON(很常见)就**整段当 reply**,情绪走关键词兜底 —— 不因为格式不对就不回答。
|
|
222
|
-
*/
|
|
223
|
-
export function parseReplyText(text) {
|
|
224
|
-
const raw = String(text ?? '');
|
|
225
|
-
const trimmed = raw.trim();
|
|
226
|
-
if (trimmed.startsWith('{')) {
|
|
227
|
-
try {
|
|
228
|
-
const doc = JSON.parse(trimmed);
|
|
229
|
-
if (doc && typeof doc.reply === 'string') {
|
|
230
|
-
return { reply: doc.reply, emotion: EMO_CODES.includes(doc.emotion) ? doc.emotion : null };
|
|
231
|
-
}
|
|
232
|
-
} catch { /* 落到下面按纯文本处理 */ }
|
|
233
|
-
}
|
|
234
|
-
return { reply: raw, emotion: null };
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
/** 关键词兜底(导出给测试与客户端对照)。 */
|
|
238
|
-
export function emotionFromKeywords(text) {
|
|
239
|
-
const raw = String(text ?? '');
|
|
240
|
-
for (const [code, re] of EMO_KEYWORDS) if (re.test(raw)) return code;
|
|
241
|
-
return 'calm';
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
/** 状态码 → 机读错误码(工单 §2.2 的 code 集合)。 */
|
|
245
|
-
function codeForStatus(status) {
|
|
246
|
-
if (status === 401 || status === 403) return { code: 'unauthorized', hint: '检查设置里的 apiKey 是否正确' };
|
|
247
|
-
if (status === 429) return { code: 'rate-limited', hint: '模型端点限流了,等一会儿再试' };
|
|
248
|
-
return { code: 'bad-request', hint: `模型端点返回 HTTP ${status}` };
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
/** SSE 单帧。 */
|
|
252
|
-
function sse(res, event, data) {
|
|
253
|
-
res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
/** 读请求体(JSON;超过上限直接拒绝)。 */
|
|
257
|
-
function readJsonBody(req, limitBytes = 16 * 1024) {
|
|
258
|
-
return new Promise((resolve, reject) => {
|
|
259
|
-
let size = 0;
|
|
260
|
-
let tooLarge = false;
|
|
261
|
-
const chunks = [];
|
|
262
|
-
req.on('data', (chunk) => {
|
|
263
|
-
size += chunk.length;
|
|
264
|
-
if (size > limitBytes) {
|
|
265
|
-
// 超限**只丢数据、不断连接**:`req.destroy()` 会让客户端拿到 ECONNRESET,
|
|
266
|
-
// 浏览器那边表现成 "fetch failed",看起来像服务器崩了 —— 其实是我们主动拒的。
|
|
267
|
-
tooLarge = true;
|
|
268
|
-
chunks.length = 0;
|
|
269
|
-
return;
|
|
270
|
-
}
|
|
271
|
-
if (!tooLarge) chunks.push(chunk);
|
|
272
|
-
});
|
|
273
|
-
req.on('end', () => {
|
|
274
|
-
if (tooLarge) { reject(Object.assign(new Error('body-too-large'), { code: 'bad-request' })); return; }
|
|
275
|
-
try {
|
|
276
|
-
const text = Buffer.concat(chunks).toString('utf8');
|
|
277
|
-
resolve(text ? JSON.parse(text) : {});
|
|
278
|
-
} catch { reject(Object.assign(new Error('bad-json'), { code: 'bad-request' })); }
|
|
279
|
-
});
|
|
280
|
-
req.on('error', reject);
|
|
281
|
-
});
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
/** 读原始请求体(音频;超过上限直接拒绝)。 */
|
|
285
|
-
function readRawBody(req, limitBytes = 2 * 1024 * 1024) {
|
|
286
|
-
return new Promise((resolve, reject) => {
|
|
287
|
-
let size = 0;
|
|
288
|
-
let tooLarge = false;
|
|
289
|
-
const chunks = [];
|
|
290
|
-
req.on('data', (chunk) => {
|
|
291
|
-
size += chunk.length;
|
|
292
|
-
if (size > limitBytes) { tooLarge = true; chunks.length = 0; return; }
|
|
293
|
-
if (!tooLarge) chunks.push(chunk);
|
|
294
|
-
});
|
|
295
|
-
req.on('end', () => {
|
|
296
|
-
if (tooLarge) { reject(Object.assign(new Error('body-too-large'), { code: 'bad-request' })); return; }
|
|
297
|
-
resolve(new Uint8Array(Buffer.concat(chunks)));
|
|
298
|
-
});
|
|
299
|
-
req.on('error', reject);
|
|
300
|
-
});
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
/** 只取 IP 里的地址部分(限频键)。 */
|
|
304
|
-
function sourceOf(req) {
|
|
305
|
-
return String((req.socket && req.socket.remoteAddress) || 'unknown');
|
|
306
|
-
}
|
|
307
|
-
|
|
308
|
-
/**
|
|
309
|
-
* 把一次流式响应按 provider 解成纯文本增量。
|
|
310
|
-
*
|
|
311
|
-
* ollama:整行 JSON `{"message":{"content":"…"},"done":false}`
|
|
312
|
-
* openai:`data: {"choices":[{"delta":{"content":"…"}}]}` / `data: [DONE]`
|
|
313
|
-
* 两种都容忍空行与心跳注释(`: keep-alive`)。
|
|
314
|
-
*/
|
|
315
|
-
function* decodeStreamChunk(provider, line) {
|
|
316
|
-
const raw = String(line ?? '').trim();
|
|
317
|
-
if (!raw || raw.startsWith(':')) return;
|
|
318
|
-
const payload = raw.startsWith('data:') ? raw.slice(5).trim() : raw;
|
|
319
|
-
if (!payload || payload === '[DONE]') return;
|
|
320
|
-
let doc;
|
|
321
|
-
try { doc = JSON.parse(payload); } catch { return; }
|
|
322
|
-
if (provider === 'ollama') {
|
|
323
|
-
const piece = doc && doc.message && typeof doc.message.content === 'string' ? doc.message.content : '';
|
|
324
|
-
if (piece) yield piece;
|
|
325
|
-
return;
|
|
326
|
-
}
|
|
327
|
-
const choice = doc && Array.isArray(doc.choices) ? doc.choices[0] : null;
|
|
328
|
-
const piece = choice && choice.delta && typeof choice.delta.content === 'string' ? choice.delta.content : '';
|
|
329
|
-
if (piece) yield piece;
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
export function registerPetChatRoutes(webServer, c) {
|
|
333
|
-
const { disposers, base: BASE, log, readSettings, speechToText } = c;
|
|
334
|
-
|
|
335
|
-
/** 宿主侧录音器:**必须在这里实例化** —— 只 import 不 new,/record 会抛
|
|
336
|
-
* ReferenceError: voiceRecorder is not defined(P6 实锤)。 */
|
|
337
|
-
const voiceRecorder = createVoiceRecorder({
|
|
338
|
-
resolveFfmpeg: defaultResolveFfmpeg,
|
|
339
|
-
runFfmpeg: defaultRunFfmpeg,
|
|
340
|
-
});
|
|
341
|
-
|
|
342
|
-
/** 当前进程内的会话记忆(重启即忘;`/reset` 清空)。 */
|
|
343
|
-
let memory = [];
|
|
344
|
-
/** 轮次计数(摘要触发用)与最近一次摘要时间。 */
|
|
345
|
-
let turnCount = 0;
|
|
346
|
-
let lastMemoryAt = 0;
|
|
347
|
-
/** 同一来源的最近一次请求时间(限频)。 */
|
|
348
|
-
const lastAt = new Map();
|
|
349
|
-
/** 转写限频(1 次 / 2 秒):同一来源一张表。 */
|
|
350
|
-
const asrLastAt = new Map();
|
|
351
|
-
/** 最近一次失败原因(`/state` 里回给界面)。 */
|
|
352
|
-
let lastError = null;
|
|
353
|
-
|
|
354
|
-
/**
|
|
355
|
-
* 面板保存的覆盖层(`<DSH_FOLIA_HOME>/pet-chat/settings.json`)。
|
|
356
|
-
*
|
|
357
|
-
* 为什么不用 DSH 的设置服务:插件这边只拿到了 `readSettings`(只读),没有写入口;
|
|
358
|
-
* 桌宠面板又必须能改(开启对话 / 换模型 / 填 key 都在这里)。所以沿用 `/pets/config`
|
|
359
|
-
* 的做法,用一个插件自己的配置文件当**覆盖层**:
|
|
360
|
-
* · 读:schema 默认值 → DSH 设置 → 本文件(后者优先)
|
|
361
|
-
* · 写:只写本文件,不动 DSH 的设置档
|
|
362
|
-
* 好处是面板保存立刻生效、且插件卸载时删掉文件就回到 DSH 设置。
|
|
363
|
-
*/
|
|
364
|
-
function overlayPath() {
|
|
365
|
-
const base = process.env.DSH_FOLIA_HOME || join(homedir(), '.dsh-folia');
|
|
366
|
-
return join(base, 'pet-chat', 'settings.json');
|
|
367
|
-
}
|
|
368
|
-
|
|
369
|
-
function readOverlay() {
|
|
370
|
-
try {
|
|
371
|
-
const file = overlayPath();
|
|
372
|
-
if (!existsSync(file)) return null;
|
|
373
|
-
const doc = JSON.parse(readFileSync(file, 'utf8'));
|
|
374
|
-
return doc && typeof doc === 'object' ? doc : null;
|
|
375
|
-
} catch { return null; }
|
|
376
|
-
}
|
|
377
|
-
|
|
378
|
-
function writeOverlay(patch) {
|
|
379
|
-
const file = overlayPath();
|
|
380
|
-
const current = readOverlay() || {};
|
|
381
|
-
const next = { ...current, ...patch };
|
|
382
|
-
mkdirSync(dirname(file), { recursive: true });
|
|
383
|
-
writeFileSync(file, JSON.stringify(next, null, 2));
|
|
384
|
-
return next;
|
|
385
|
-
}
|
|
386
|
-
|
|
387
|
-
/** 读当前 petChat 配置(每次现读:设置面板改完立刻生效,不用重启)。 */
|
|
388
|
-
function readPetChat() {
|
|
389
|
-
let settings = null;
|
|
390
|
-
try { settings = readSettings(); } catch (error) {
|
|
391
|
-
// 读设置失败不能让整条链路炸:当作默认(关)
|
|
392
|
-
log('[pet-chat] 读设置失败:' + String((error && error.message) || error));
|
|
393
|
-
}
|
|
394
|
-
const schemaRaw = settings && typeof settings === 'object' && settings.petChat && typeof settings.petChat === 'object'
|
|
395
|
-
? settings.petChat : {};
|
|
396
|
-
// 旧键映射只写一处:settings-schema 的 readPetChat 同时负责"默认值 + 迁移"
|
|
397
|
-
const normalized = normalizePetChat({ ...schemaRaw, ...(readOverlay() || {}) });
|
|
398
|
-
const provider = normalized.provider === 'openai' ? 'openai' : 'ollama';
|
|
399
|
-
const defaults = PROVIDER_DEFAULTS[provider];
|
|
400
|
-
const baseUrl = typeof normalized.baseUrl === 'string' && normalized.baseUrl.trim() ? normalized.baseUrl.trim() : defaults.baseUrl;
|
|
401
|
-
return {
|
|
402
|
-
enabled: normalized.enabled === true,
|
|
403
|
-
provider,
|
|
404
|
-
baseUrl: baseUrl.replace(/\/+$/, ''),
|
|
405
|
-
apiKey: normalized.apiKey,
|
|
406
|
-
model: typeof normalized.model === 'string' && normalized.model.trim() ? normalized.model.trim() : defaults.model,
|
|
407
|
-
// v0.1 设置收敛:名字两项 + 音色两项 + 唤醒三项,其余(轮数/字数)是代码常量
|
|
408
|
-
petName: normalized.petName,
|
|
409
|
-
ownerName: normalized.ownerName,
|
|
410
|
-
voice: normalized.voice,
|
|
411
|
-
wake: normalized.wake,
|
|
412
|
-
// 记忆常开(零配置):设置里没有开关
|
|
413
|
-
memoryEnabled: true,
|
|
414
|
-
// 实现细节:不再暴露给用户,也不再从设置里读
|
|
415
|
-
maxTurns: DEFAULT_MAX_TURNS,
|
|
416
|
-
maxChars: DEFAULT_MAX_CHARS,
|
|
417
|
-
// 内部旋钮:不进 UI,但保留可配置(测试与排障用)
|
|
418
|
-
memoryEveryTurns: (() => {
|
|
419
|
-
const raw = Number((readOverlay() || {}).memoryEveryTurns ?? schemaRaw.memoryEveryTurns);
|
|
420
|
-
return Number.isFinite(raw) && raw > 0 ? Math.min(50, raw) : DEFAULT_MEMORY_EVERY_TURNS;
|
|
421
|
-
})(),
|
|
422
|
-
};
|
|
423
|
-
}
|
|
424
|
-
|
|
425
|
-
/** 组装请求体(两种协议各一份;都只发到配置里的端点)。 */
|
|
426
|
-
function buildRequest(config, text) {
|
|
427
|
-
// v0.1:人设不再是一长串设置,只有"名字 / 主人称呼"两项;风格走内置文案
|
|
428
|
-
const petName = config.petName || 'Folia';
|
|
429
|
-
const ownerName = config.ownerName ? `,称呼用户为「${config.ownerName}」` : '';
|
|
430
|
-
let system = `你是${petName}${ownerName},元气、短句、偶尔颜文字、不说教;`
|
|
431
|
-
+ '你的特点:喜欢壁纸和游戏,被夸会害羞。'
|
|
432
|
-
+ `用中文口语回答,最多 ${config.maxChars} 字,不用 Markdown。`
|
|
433
|
-
|
|
434
|
-
// 工单 A5⑤ 的判据是「第 9 轮只带最近 8 条」⇒ 上限按**条**算(一问一答 = 2 条)
|
|
435
|
-
// B3:把长期偏好注入 system prompt(≤80 字;记忆为空时这一行为空)
|
|
436
|
-
const memoryLine = config.memoryEnabled ? memoryPromptLine(readMemory()) : '';
|
|
437
|
-
if (memoryLine) system += '\n' + memoryLine;
|
|
438
|
-
const history = memory.slice(-config.maxTurns);
|
|
439
|
-
const headers = { 'content-type': 'application/json' };
|
|
440
|
-
if (config.provider === 'openai') {
|
|
441
|
-
if (config.apiKey) headers.authorization = `Bearer ${config.apiKey}`;
|
|
442
|
-
return {
|
|
443
|
-
url: `${config.baseUrl}/chat/completions`,
|
|
444
|
-
body: {
|
|
445
|
-
model: config.model,
|
|
446
|
-
stream: true,
|
|
447
|
-
temperature: 0.8,
|
|
448
|
-
messages: [{ role: 'system', content: system }, ...history, { role: 'user', content: text }],
|
|
449
|
-
},
|
|
450
|
-
headers,
|
|
451
|
-
};
|
|
452
|
-
}
|
|
453
|
-
return {
|
|
454
|
-
url: `${config.baseUrl}/api/chat`,
|
|
455
|
-
body: {
|
|
456
|
-
model: config.model,
|
|
457
|
-
stream: true,
|
|
458
|
-
messages: [{ role: 'system', content: system }, ...history, { role: 'user', content: text }],
|
|
459
|
-
},
|
|
460
|
-
headers,
|
|
461
|
-
};
|
|
462
|
-
}
|
|
463
|
-
|
|
464
|
-
/** GET /pet-chat/state */
|
|
465
|
-
async function handleState(res) {
|
|
466
|
-
const config = readPetChat();
|
|
467
|
-
let reachable = false;
|
|
468
|
-
if (config.enabled) {
|
|
469
|
-
const controller = new AbortController();
|
|
470
|
-
const timer = setTimeout(() => controller.abort(), 1500);
|
|
471
|
-
try {
|
|
472
|
-
const probe = config.provider === 'ollama' ? `${config.baseUrl}/api/tags` : `${config.baseUrl}/models`;
|
|
473
|
-
const headers = {};
|
|
474
|
-
if (config.provider === 'openai' && config.apiKey) headers.authorization = `Bearer ${config.apiKey}`;
|
|
475
|
-
const response = await fetch(probe, { headers, signal: controller.signal });
|
|
476
|
-
reachable = response.ok;
|
|
477
|
-
if (!response.ok) lastError = codeForStatus(response.status).code;
|
|
478
|
-
} catch {
|
|
479
|
-
reachable = false;
|
|
480
|
-
lastError = 'unreachable';
|
|
481
|
-
} finally {
|
|
482
|
-
clearTimeout(timer);
|
|
483
|
-
}
|
|
484
|
-
}
|
|
485
|
-
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
486
|
-
res.end(JSON.stringify({
|
|
487
|
-
ok: true,
|
|
488
|
-
enabled: config.enabled,
|
|
489
|
-
provider: config.provider,
|
|
490
|
-
model: config.model,
|
|
491
|
-
reachable,
|
|
492
|
-
lastError,
|
|
493
|
-
// v0.1:语音输入开关随设置收敛去掉(能力由 DSH 决定);语音/名字照旧回给客户端
|
|
494
|
-
petName: config.petName,
|
|
495
|
-
ownerName: config.ownerName,
|
|
496
|
-
voice: config.voice,
|
|
497
|
-
memoryEnabled: config.memoryEnabled,
|
|
498
|
-
asrProvider: ASR_PROVIDER_ID,
|
|
499
|
-
}));
|
|
500
|
-
}
|
|
501
|
-
|
|
502
|
-
/** GET /pet-chat/models */
|
|
503
|
-
async function handleModels(res) {
|
|
504
|
-
const config = readPetChat();
|
|
505
|
-
const send = (payload) => {
|
|
506
|
-
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
507
|
-
res.end(JSON.stringify(payload));
|
|
508
|
-
};
|
|
509
|
-
if (config.provider === 'openai') {
|
|
510
|
-
send({ ok: true, provider: 'openai', models: [], hint: 'OpenAI 兼容端点不提供模型列表,直接在设置里填模型名' });
|
|
511
|
-
return;
|
|
512
|
-
}
|
|
513
|
-
const controller = new AbortController();
|
|
514
|
-
const timer = setTimeout(() => controller.abort(), 4000);
|
|
515
|
-
try {
|
|
516
|
-
const response = await fetch(`${config.baseUrl}/api/tags`, { signal: controller.signal });
|
|
517
|
-
if (!response.ok) { send({ ok: false, provider: 'ollama', models: [], hint: `HTTP ${response.status}` }); return; }
|
|
518
|
-
const doc = await response.json();
|
|
519
|
-
const models = (doc && Array.isArray(doc.models) ? doc.models : [])
|
|
520
|
-
.map((item) => (item && typeof item.name === 'string' ? item.name : null))
|
|
521
|
-
.filter(Boolean);
|
|
522
|
-
send({ ok: true, provider: 'ollama', models });
|
|
523
|
-
} catch {
|
|
524
|
-
send({ ok: false, provider: 'ollama', models: [], hint: '连不上本机 Ollama(127.0.0.1:11434)' });
|
|
525
|
-
} finally {
|
|
526
|
-
clearTimeout(timer);
|
|
527
|
-
}
|
|
528
|
-
}
|
|
529
|
-
|
|
530
|
-
/** POST /pet-chat/chat(SSE) */
|
|
531
|
-
async function handleChat(req, res) {
|
|
532
|
-
const ip = sourceOf(req);
|
|
533
|
-
const now = Date.now();
|
|
534
|
-
const prev = lastAt.get(ip) || 0;
|
|
535
|
-
res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
|
|
536
|
-
res.setHeader('Cache-Control', 'no-cache');
|
|
537
|
-
res.setHeader('Connection', 'keep-alive');
|
|
538
|
-
res.setHeader('X-Accel-Buffering', 'no');
|
|
539
|
-
const fail = (code, hint) => {
|
|
540
|
-
lastError = code;
|
|
541
|
-
sse(res, 'error', { code, hint });
|
|
542
|
-
res.end();
|
|
543
|
-
};
|
|
544
|
-
|
|
545
|
-
if (now - prev < RATE_LIMIT_MS) { fail('rate-limited', '一秒一次,慢点~'); return; }
|
|
546
|
-
lastAt.set(ip, now);
|
|
547
|
-
|
|
548
|
-
let body;
|
|
549
|
-
try { body = await readJsonBody(req); } catch { fail('bad-request', '请求体不是合法 JSON'); return; }
|
|
550
|
-
const text = typeof body.text === 'string' ? body.text.trim() : '';
|
|
551
|
-
if (!text) { fail('bad-request', '说点什么吧'); return; }
|
|
552
|
-
if ([...text].length > MAX_INPUT_CHARS) { fail('bad-request', `一次最多 ${MAX_INPUT_CHARS} 字`); return; }
|
|
553
|
-
|
|
554
|
-
const config = readPetChat();
|
|
555
|
-
if (!config.enabled) { fail('no-model', '先在设置里打开桌宠对话并填一个模型'); return; }
|
|
556
|
-
|
|
557
|
-
/**
|
|
558
|
-
* 语音/打字指令:**说"别说了"就静默**(到次日 0 点),说"可以说话了"就恢复。
|
|
559
|
-
* 这是「零配置」里用户唯一的控制方式(追加决定 2),所以在这里拦一道,
|
|
560
|
-
* 命中就不调模型(省 token,也让响应立刻生效)。
|
|
561
|
-
*/
|
|
562
|
-
const command = parseSilenceCommand(text);
|
|
563
|
-
if (command === 'silence') {
|
|
564
|
-
enterSilence();
|
|
565
|
-
res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
|
|
566
|
-
sse(res, 'delta', { t: '好,那我安静一会儿。' });
|
|
567
|
-
sse(res, 'done', { emotion: 'calm', command: 'silence' });
|
|
568
|
-
res.end();
|
|
569
|
-
return;
|
|
570
|
-
}
|
|
571
|
-
if (command === 'resume') {
|
|
572
|
-
clearSilence();
|
|
573
|
-
res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
|
|
574
|
-
sse(res, 'delta', { t: '好,我回来了。' });
|
|
575
|
-
sse(res, 'done', { emotion: 'happy', command: 'resume' });
|
|
576
|
-
res.end();
|
|
577
|
-
return;
|
|
578
|
-
}
|
|
579
|
-
|
|
580
|
-
if (config.provider === 'openai' && !config.apiKey) {
|
|
581
|
-
fail('no-model', '填 DeepSeek API Key 即可对话(也可改用本机 Ollama,检测到 127.0.0.1:11434 时会提示)');
|
|
582
|
-
return;
|
|
583
|
-
}
|
|
584
|
-
|
|
585
|
-
const request = buildRequest(config, text);
|
|
586
|
-
const controller = new AbortController();
|
|
587
|
-
const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
|
|
588
|
-
let finished = false;
|
|
589
|
-
const done = (emotion, usage) => {
|
|
590
|
-
if (finished) return;
|
|
591
|
-
finished = true;
|
|
592
|
-
sse(res, 'done', { emotion, usage: usage || null });
|
|
593
|
-
res.end();
|
|
594
|
-
};
|
|
595
|
-
|
|
596
|
-
try {
|
|
597
|
-
const response = await fetch(request.url, {
|
|
598
|
-
method: 'POST',
|
|
599
|
-
headers: request.headers,
|
|
600
|
-
body: JSON.stringify(request.body),
|
|
601
|
-
signal: controller.signal,
|
|
602
|
-
});
|
|
603
|
-
if (!response.ok) {
|
|
604
|
-
const mapped = codeForStatus(response.status);
|
|
605
|
-
fail(mapped.code, mapped.hint);
|
|
606
|
-
return;
|
|
607
|
-
}
|
|
608
|
-
const reader = response.body.getReader();
|
|
609
|
-
const decoder = new TextDecoder();
|
|
610
|
-
let buffer = '';
|
|
611
|
-
let full = '';
|
|
612
|
-
for (;;) {
|
|
613
|
-
// eslint-disable-next-line no-await-in-loop -- 流式读取必须逐块等
|
|
614
|
-
const { value, done: ended } = await reader.read();
|
|
615
|
-
if (ended) break;
|
|
616
|
-
buffer += decoder.decode(value, { stream: true });
|
|
617
|
-
const lines = buffer.split('\n');
|
|
618
|
-
buffer = lines.pop() ?? '';
|
|
619
|
-
for (const line of lines) {
|
|
620
|
-
for (const piece of decodeStreamChunk(config.provider, line)) {
|
|
621
|
-
// 回复长度上限(工单 A5⑥):超了就**在流里截断**,不把超长内容推给气泡,
|
|
622
|
-
// 也不假装没发生 —— 截断处就是 done,客户端拿到的长度恒 ≤ maxChars。
|
|
623
|
-
const room = config.maxChars - full.length;
|
|
624
|
-
if (room <= 0) break;
|
|
625
|
-
const chunk = piece.length > room ? piece.slice(0, room) : piece;
|
|
626
|
-
full += chunk;
|
|
627
|
-
sse(res, 'delta', { t: chunk });
|
|
628
|
-
if (full.length >= config.maxChars) break;
|
|
629
|
-
}
|
|
630
|
-
}
|
|
631
|
-
}
|
|
632
|
-
const parsed = parseReplyText(full);
|
|
633
|
-
const emotion = parsed.emotion || emotionFromKeywords(parsed.reply);
|
|
634
|
-
// B2①:用户显式说「记住…」⇒ 立刻写记忆(只存结论)
|
|
635
|
-
if (config.memoryEnabled) {
|
|
636
|
-
const explicit = parseExplicitMemory(text);
|
|
637
|
-
if (explicit) rememberExplicit(readMemory(), explicit);
|
|
638
|
-
}
|
|
639
|
-
memory.push({ role: 'user', content: text });
|
|
640
|
-
memory.push({ role: 'assistant', content: parsed.reply });
|
|
641
|
-
turnCount += 1;
|
|
642
|
-
// B2②:每 N 轮让模型吐一次摘要 ⇒ 合并去重(不覆盖显式项)
|
|
643
|
-
if (config.memoryEnabled && turnCount % config.memoryEveryTurns === 0) {
|
|
644
|
-
const merged = await summarizeMemory(config, memory.slice(-config.maxTurns));
|
|
645
|
-
if (merged) lastMemoryAt = Date.now();
|
|
646
|
-
}
|
|
647
|
-
if (memory.length > MAX_MEMORY_TURNS * 2) memory = memory.slice(-MAX_MEMORY_TURNS * 2);
|
|
648
|
-
done(emotion, { chars: parsed.reply.length });
|
|
649
|
-
} catch (error) {
|
|
650
|
-
if (error && error.name === 'AbortError') fail('timeout', '模型 20 秒没回应,再试一次');
|
|
651
|
-
else fail('bad-request', '连不上模型端点,检查设置里的地址');
|
|
652
|
-
} finally {
|
|
653
|
-
clearTimeout(timer);
|
|
654
|
-
}
|
|
655
|
-
}
|
|
656
|
-
|
|
657
|
-
/**
|
|
658
|
-
* B2②:让模型对最近几轮做一次**偏好提炼**(非流式,独立请求)。
|
|
659
|
-
* 失败一律吞掉(记忆是加分项,不能因为它把聊天弄挂)。
|
|
660
|
-
*/
|
|
661
|
-
async function summarizeMemory(config, history) {
|
|
662
|
-
try {
|
|
663
|
-
const controller = new AbortController();
|
|
664
|
-
const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
|
|
665
|
-
const headers = { 'content-type': 'application/json' };
|
|
666
|
-
if (config.provider === 'openai' && config.apiKey) headers.authorization = `Bearer ${config.apiKey}`;
|
|
667
|
-
const url = config.provider === 'ollama' ? `${config.baseUrl}/api/chat` : `${config.baseUrl}/chat/completions`;
|
|
668
|
-
const body = {
|
|
669
|
-
model: config.model,
|
|
670
|
-
stream: false,
|
|
671
|
-
messages: [{ role: 'system', content: MEMORY_SUMMARY_PROMPT }, ...history],
|
|
672
|
-
};
|
|
673
|
-
const response = await fetch(url, { method: 'POST', headers, body: JSON.stringify(body), signal: controller.signal });
|
|
674
|
-
clearTimeout(timer);
|
|
675
|
-
if (!response.ok) return null;
|
|
676
|
-
const doc = await response.json();
|
|
677
|
-
const content = config.provider === 'ollama'
|
|
678
|
-
? (doc && doc.message && doc.message.content)
|
|
679
|
-
: (doc && doc.choices && doc.choices[0] && doc.choices[0].message && doc.choices[0].message.content);
|
|
680
|
-
if (typeof content !== 'string') return null;
|
|
681
|
-
const jsonStart = content.indexOf('{');
|
|
682
|
-
const jsonEnd = content.lastIndexOf('}');
|
|
683
|
-
if (jsonStart < 0 || jsonEnd <= jsonStart) return null;
|
|
684
|
-
const summary = JSON.parse(content.slice(jsonStart, jsonEnd + 1));
|
|
685
|
-
return mergeSummary(readMemory(), summary);
|
|
686
|
-
} catch {
|
|
687
|
-
return null;
|
|
688
|
-
}
|
|
689
|
-
}
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
/**
|
|
693
|
-
* POST /pet-chat/transcribe —— 把一段 WAV 交给 DSH 宿主的转写服务。
|
|
694
|
-
*
|
|
695
|
-
* 为什么不在插件里带模型:DSH 已经有 `ctx.speechToText`(provider 自己下载并校验模型)。
|
|
696
|
-
* 插件这边只做「收音频 → 校验 → 转发 → 回文本」四件事,序列化与推理都不碰。
|
|
697
|
-
*
|
|
698
|
-
* 返回(**一律 200**,除参数不合法):
|
|
699
|
-
* · 成功 `{ ok:true, text, audioSeconds, inferenceSeconds }`
|
|
700
|
-
* · 未就绪 `{ ok:false, code:'asr-not-ready', hint:'请在 DSH 设置启用语音输入(需下载模型)' }`
|
|
701
|
-
* · 超时取消 `{ ok:false, code:'asr-timeout' }`
|
|
702
|
-
* 参数不合法(超长/超大/不是 WAV)走 400 `bad-request` —— 那是客户端 bug,不是环境问题。
|
|
703
|
-
*/
|
|
704
|
-
async function handleTranscribe(req, res) {
|
|
705
|
-
const ip = sourceOf(req);
|
|
706
|
-
const send = (payload, status = 200) => {
|
|
707
|
-
res.statusCode = status;
|
|
708
|
-
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
709
|
-
res.end(JSON.stringify(payload));
|
|
710
|
-
};
|
|
711
|
-
|
|
712
|
-
// 两种入参:JSON `{audio: base64, language}` 或原始 WAV 体(content-type: audio/wav)
|
|
713
|
-
const contentType = String(req.headers['content-type'] || '').toLowerCase();
|
|
714
|
-
let audio;
|
|
715
|
-
let language = 'zh';
|
|
716
|
-
try {
|
|
717
|
-
if (contentType.includes('audio/')) {
|
|
718
|
-
audio = new Uint8Array(await readRawBody(req, ASR_MAX_BYTES + 1));
|
|
719
|
-
} else {
|
|
720
|
-
const body = await readJsonBody(req, ASR_MAX_BYTES + 4096);
|
|
721
|
-
if (typeof body.audio === 'string') audio = decodeBase64(body.audio);
|
|
722
|
-
else if (Array.isArray(body.audio)) audio = Uint8Array.from(body.audio);
|
|
723
|
-
else audio = new Uint8Array(0);
|
|
724
|
-
if (typeof body.language === 'string' && body.language) language = body.language.slice(0, 8);
|
|
725
|
-
}
|
|
726
|
-
} catch {
|
|
727
|
-
send({ ok: false, code: 'bad-request', hint: '请求体不是合法的 JSON / 音频' }, 400);
|
|
728
|
-
return;
|
|
729
|
-
}
|
|
730
|
-
|
|
731
|
-
if (!audio || !audio.byteLength) { send({ ok: false, code: 'bad-request', hint: '音频为空' }, 400); return; }
|
|
732
|
-
if (audio.byteLength > ASR_MAX_BYTES) { send({ ok: false, code: 'bad-request', hint: '音频超过 2MB' }, 400); return; }
|
|
733
|
-
const seconds = wavSeconds(audio);
|
|
734
|
-
if (seconds === null) { send({ ok: false, code: 'bad-request', hint: '只接受 16kHz 单声道 PCM16 WAV' }, 400); return; }
|
|
735
|
-
if (seconds > ASR_MAX_SECONDS) {
|
|
736
|
-
send({ ok: false, code: 'bad-request', hint: `单段最多 ${ASR_MAX_SECONDS} 秒(这段 ${seconds.toFixed(1)} 秒)` }, 400);
|
|
737
|
-
return;
|
|
738
|
-
}
|
|
739
|
-
|
|
740
|
-
// 参数都合法了才计入限频:坏请求不占配额
|
|
741
|
-
const lastAtMs = asrLastAt.get(ip) || 0;
|
|
742
|
-
const nowMs = Date.now();
|
|
743
|
-
if (nowMs - lastAtMs < ASR_RATE_LIMIT_MS) {
|
|
744
|
-
send({ ok: false, code: 'rate-limited', hint: '2 秒内最多转写一次' });
|
|
745
|
-
return;
|
|
746
|
-
}
|
|
747
|
-
asrLastAt.set(ip, nowMs);
|
|
748
|
-
|
|
749
|
-
// ① 服务可能压根没装(用户没启用「语音输入」实验特性)
|
|
750
|
-
// 本地 STT 优先:收到的是 WAV 字节 ⇒ 落临时文件交给 worker 识别
|
|
751
|
-
if (await localAsrReady()) {
|
|
752
|
-
try {
|
|
753
|
-
const dir = mkdtempSync(join(tmpdir(), 'folia-asr-'));
|
|
754
|
-
const wavPath = join(dir, 'input.wav');
|
|
755
|
-
writeFileSync(wavPath, Buffer.from(audio));
|
|
756
|
-
const worker = await ensureLocalAsr();
|
|
757
|
-
const spoken = await worker.request(wavPath, ASR_TIMEOUT_MS);
|
|
758
|
-
try { rmSync(dir, { recursive: true, force: true }); } catch { /* ignore */ }
|
|
759
|
-
if (!spoken || !spoken.ok) { send({ ok: false, code: 'asr-failed', hint: '识别失败,再试一次' }, 502); return; }
|
|
760
|
-
const text = String(spoken.text || '').trim();
|
|
761
|
-
if (!text) { send({ ok: false, code: 'no-speech', hint: '没听清,再说一次' }, 422); return; }
|
|
762
|
-
send({ ok: true, text, ms: spoken.ms, seconds });
|
|
763
|
-
return;
|
|
764
|
-
} catch {
|
|
765
|
-
// 落到下面的 DSH 服务路径
|
|
766
|
-
}
|
|
767
|
-
}
|
|
768
|
-
const service = speechToText;
|
|
769
|
-
if (!service || typeof service.snapshot !== 'function' || typeof service.transcribe !== 'function') {
|
|
770
|
-
send({ ok: false, code: 'asr-not-ready', hint: ASR_NOT_READY_HINT });
|
|
771
|
-
return;
|
|
772
|
-
}
|
|
773
|
-
|
|
774
|
-
// ② 服务装了,但 provider 没就绪(没下载 / 正在下 / 加载失败)——用快照判断,不要靠 try/catch 猜
|
|
775
|
-
let phase = 'missing';
|
|
776
|
-
try {
|
|
777
|
-
const snapshot = service.snapshot();
|
|
778
|
-
const provider = (snapshot && Array.isArray(snapshot.providers) ? snapshot.providers : [])
|
|
779
|
-
.find((item) => item && item.id === ASR_PROVIDER_ID);
|
|
780
|
-
phase = provider && provider.preparation ? provider.preparation.phase : 'missing';
|
|
781
|
-
} catch (error) {
|
|
782
|
-
log('[pet-chat] speechToText.snapshot 失败:' + String((error && error.message) || error));
|
|
783
|
-
phase = 'missing';
|
|
784
|
-
}
|
|
785
|
-
if (phase !== 'ready') {
|
|
786
|
-
send({
|
|
787
|
-
ok: false,
|
|
788
|
-
code: 'asr-not-ready',
|
|
789
|
-
hint: phase === 'missing'
|
|
790
|
-
? ASR_NOT_READY_HINT
|
|
791
|
-
: `${ASR_NOT_READY_HINT}(当前状态:${phase})`,
|
|
792
|
-
phase,
|
|
793
|
-
});
|
|
794
|
-
return;
|
|
795
|
-
}
|
|
796
|
-
|
|
797
|
-
// ③ 就绪:resolve 出 provider-pinned spec,再执行
|
|
798
|
-
let spec;
|
|
799
|
-
try {
|
|
800
|
-
spec = service.resolve({ audio, language: ASR_LANGUAGE, providerId: ASR_PROVIDER_ID });
|
|
801
|
-
} catch (error) {
|
|
802
|
-
send({ ok: false, code: 'asr-not-ready', hint: ASR_NOT_READY_HINT });
|
|
803
|
-
log('[pet-chat] speechToText.resolve 失败:' + String((error && error.message) || error));
|
|
804
|
-
return;
|
|
805
|
-
}
|
|
806
|
-
|
|
807
|
-
const controller = new AbortController();
|
|
808
|
-
const timer = setTimeout(() => controller.abort(), ASR_TIMEOUT_MS);
|
|
809
|
-
try {
|
|
810
|
-
const transcript = await service.transcribe(spec, controller.signal);
|
|
811
|
-
send({
|
|
812
|
-
ok: true,
|
|
813
|
-
text: String((transcript && transcript.text) || ''),
|
|
814
|
-
audioSeconds: Number((transcript && transcript.audioSeconds) || seconds),
|
|
815
|
-
inferenceSeconds: Number((transcript && transcript.inferenceSeconds) || 0),
|
|
816
|
-
});
|
|
817
|
-
} catch (error) {
|
|
818
|
-
const aborted = controller.signal.aborted || (error && error.name === 'AbortError');
|
|
819
|
-
send(aborted
|
|
820
|
-
? { ok: false, code: 'asr-timeout', hint: '转写超时,再试一次' }
|
|
821
|
-
: { ok: false, code: 'asr-failed', hint: '转写失败,可以改用打字' });
|
|
822
|
-
} finally {
|
|
823
|
-
clearTimeout(timer);
|
|
824
|
-
}
|
|
825
|
-
}
|
|
826
|
-
|
|
827
|
-
/** Uint8Array → base64(Node 与 Worker 都能用)。 */
|
|
828
|
-
function toBase64(bytes) {
|
|
829
|
-
if (!bytes || !bytes.byteLength) return '';
|
|
830
|
-
if (typeof Buffer !== 'undefined') return Buffer.from(bytes).toString('base64');
|
|
831
|
-
let binary = '';
|
|
832
|
-
for (let i = 0; i < bytes.length; i += 1) binary += String.fromCharCode(bytes[i]);
|
|
833
|
-
return btoa(binary);
|
|
834
|
-
}
|
|
835
|
-
|
|
836
|
-
/**
|
|
837
|
-
* 设置面板用的读写接口。
|
|
838
|
-
*
|
|
839
|
-
* GET /pet-chat/config 回完整配置(apiKey 只回掩码 + hasApiKey)
|
|
840
|
-
* POST /pet-chat/config 保存(写覆盖层;provider=ollama 时强制默认地址、清空 key)
|
|
841
|
-
* POST /pet-chat/test 真连一次 provider,失败给具体原因(401/402/超时/地址错)
|
|
842
|
-
* DELETE /pet-chat/memory 只清记忆,不动对话与设置
|
|
843
|
-
*/
|
|
844
|
-
/**
|
|
845
|
-
* POST /pet-chat/record —— 宿主侧录一段,然后走现有 speechToText 转写。
|
|
846
|
-
* 前端不再碰 getUserMedia(Electron 权限只放行 clipboard/notifications)。
|
|
847
|
-
*/
|
|
848
|
-
async function handleRecord(req, res) {
|
|
849
|
-
let body = {};
|
|
850
|
-
try { body = await readJsonBody(req); } catch { body = {}; }
|
|
851
|
-
const result = await voiceRecorder.record({
|
|
852
|
-
maxMs: Number(body.maxMs) || undefined,
|
|
853
|
-
silenceDb: body.silenceDb === undefined ? undefined : Number(body.silenceDb),
|
|
854
|
-
silenceMs: Number(body.silenceMs) || undefined,
|
|
855
|
-
});
|
|
856
|
-
const send = (payload, status = 200) => {
|
|
857
|
-
res.statusCode = status;
|
|
858
|
-
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
859
|
-
res.end(JSON.stringify(payload));
|
|
860
|
-
};
|
|
861
|
-
if (!result.ok) {
|
|
862
|
-
const hints = {
|
|
1
|
+
/**
|
|
2
|
+
* routes/pet-chat.js — **桌宠对话**路由族:`/pet-chat/*`(门 2 / 任务 A2)。
|
|
3
|
+
*
|
|
4
|
+
* 四条端点(契约见插件仓库 docs/PET-CHAT-PLAN.md §2.2):
|
|
5
|
+
* GET /folia/pet-chat/state → { enabled, provider, model, reachable, lastError }
|
|
6
|
+
* GET /folia/pet-chat/models → ollama 的 /api/tags 列表(openai 返回空 + hint)
|
|
7
|
+
* POST /folia/pet-chat/chat → SSE:event: delta {"t"} / done {usage,emotion} / error {code,hint}
|
|
8
|
+
* POST /folia/pet-chat/reset → 清空会话记忆
|
|
9
|
+
*
|
|
10
|
+
* 纪律(工单 §2.2 的约束,逐条对上):
|
|
11
|
+
* · **只转发到用户配置的端点**:baseUrl 来自设置(空 = 该 provider 的默认端点),
|
|
12
|
+
* 不接受请求体里带 URL —— 否则这个路由会变成任意转发器。
|
|
13
|
+
* · **超时 20s**:AbortController;到点即发 `error{code:'timeout'}` 并断流。
|
|
14
|
+
* · **限频 1 次/秒**(同一来源 IP):超了直接 `error{code:'rate-limited'}`,不再打模型。
|
|
15
|
+
* · **输入 ≤400 字**:超长 `error{code:'bad-request'}`(客户端也会截断,这里是服务端兜底)。
|
|
16
|
+
* · **key 不进日志**:本文件**一行都不打印** apiKey / 请求头;错误文案只带状态码。
|
|
17
|
+
* · 会话记忆在**宿主进程内存**里(reset 清空),不落盘:重启即忘,符合"只在本次会话里聊"。
|
|
18
|
+
*
|
|
19
|
+
* 依赖面(与 test/verify-inject-contracts.mjs 双向对账):`disposers` / `base` / `log` / `readSettings`。
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
/** 注入契约:本族从 `c` 消费的**必需**键(门面/注册表调用点必须逐键给到)。 */
|
|
23
|
+
// `speechToText`:DSH 宿主的转写服务(`ctx.speechToText`)。它可能**不存在**(用户没启用
|
|
24
|
+
// 「语音输入」实验特性)—— 那种情况由路由回 `asr-not-ready`,而不是启动失败。
|
|
25
|
+
export const DEPS = ['disposers', 'base', 'log', 'readSettings', 'speechToText'];
|
|
26
|
+
|
|
27
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
|
28
|
+
import { homedir, tmpdir } from 'node:os';
|
|
29
|
+
import { dirname, join } from 'node:path';
|
|
30
|
+
|
|
31
|
+
import {
|
|
32
|
+
readMemory, writeMemory, clearMemory, parseExplicitMemory, rememberExplicit,
|
|
33
|
+
mergeSummary, memoryPromptLine, MEMORY_SUMMARY_PROMPT,
|
|
34
|
+
} from '../pet-chat-memory.js';
|
|
35
|
+
// v0.1:旧键迁移与默认值只在 settings-schema 定义一次,路由复用同一个函数
|
|
36
|
+
import { readPetChat as normalizePetChat } from '../settings-schema.js';
|
|
37
|
+
import { createVoiceRecorder, defaultResolveFfmpeg, defaultRunFfmpeg } from '../voice/record.js';
|
|
38
|
+
// 本地 STT:资源不下发到 npm 包,首次使用时从站点 R2 下载(见 lib/asr/asr-local.js)
|
|
39
|
+
import { ensureInstalled as ensureAsrInstalled, startWorker as startAsrWorker } from '../asr/asr-local.js';
|
|
40
|
+
// v0.1「零配置」主动搭话:固定策略 + 语音指令静默(追加决定 1/2)
|
|
41
|
+
import {
|
|
42
|
+
canSpeak, markSaid, buildProactiveLine, readProactiveState, todayUsage, isSilent,
|
|
43
|
+
enterSilence, clearSilence, parseSilenceCommand, PROACTIVE_RULES,
|
|
44
|
+
} from '../pet-chat-proactive.js';
|
|
45
|
+
|
|
46
|
+
/** 单次输入上限(工单:≤400 字)。 */
|
|
47
|
+
const MAX_INPUT_CHARS = 400;
|
|
48
|
+
/** 模型调用超时(工单:20s)。 */
|
|
49
|
+
const TIMEOUT_MS = 20000;
|
|
50
|
+
/** 同一来源的最小间隔(工单:1 次/秒)。 */
|
|
51
|
+
const RATE_LIMIT_MS = 1000;
|
|
52
|
+
/** 会话记忆最多保留的轮数(一轮 = 一问一答)。 */
|
|
53
|
+
const MAX_MEMORY_TURNS = 12;
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* 上下文轮数 / 单条字数上限(v0.1 起不再暴露给用户)。
|
|
57
|
+
*
|
|
58
|
+
* 为什么从设置里拿掉:工单 §4「解耦」与 §5「默认值只在 settings-schema 定义一次」——
|
|
59
|
+
* 这两项属于实现细节,用户只需要"填 key、选音色、起名字"。留在设置里只会让
|
|
60
|
+
* 配置面板变成一长串旋钮(旧版本正是因为这点被推翻的)。
|
|
61
|
+
*/
|
|
62
|
+
const DEFAULT_MAX_TURNS = 8;
|
|
63
|
+
const DEFAULT_MAX_CHARS = 80;
|
|
64
|
+
/** 每 N 轮写一次记忆摘要。 */
|
|
65
|
+
const DEFAULT_MEMORY_EVERY_TURNS = 10;
|
|
66
|
+
|
|
67
|
+
/* ── 语音转写(PET-CHAT-ROUND-NEXT 之后的一轮)────────────────────────────── */
|
|
68
|
+
/** 单段音频上限:15 秒(16kHz 单声道 PCM16 ≈ 480KB)。 */
|
|
69
|
+
const ASR_MAX_SECONDS = 15;
|
|
70
|
+
/** 单段音频字节上限:2MB(工单 B 的硬约束)。 */
|
|
71
|
+
const ASR_MAX_BYTES = 2 * 1024 * 1024;
|
|
72
|
+
/** 同一来源的转写最小间隔:1 次 / 2 秒。 */
|
|
73
|
+
const ASR_RATE_LIMIT_MS = 2000;
|
|
74
|
+
/** 转写超时:模型推理可能要几秒,给 20s。 */
|
|
75
|
+
const ASR_TIMEOUT_MS = 20000;
|
|
76
|
+
/** DSH 语音输入 bundle 注册的本地 provider id(契约见 docs/ASR-INTEGRATION.md)。 */
|
|
77
|
+
const ASR_PROVIDER_ID = 'sensevoice-local';
|
|
78
|
+
/** 转写语言(本功能只做中文;要别的语种先改契约)。 */
|
|
79
|
+
const ASR_LANGUAGE = 'zh';
|
|
80
|
+
/** 未就绪时给用户的一句话(两条路径共用,避免文案漂移)。 */
|
|
81
|
+
const ASR_NOT_READY_HINT = '语音输入还没就绪:模型还没下载好,稍等一下';
|
|
82
|
+
|
|
83
|
+
/* ── 本地 STT 运行时(自带 SenseVoice,不依赖 DSH 的语音实验包)─────────────── */
|
|
84
|
+
/**
|
|
85
|
+
* 安装根:`~/.dsh-folia/asr/v1`。
|
|
86
|
+
* 首次点桌宠说话时从站点下载(约 340MB;node.exe 复用 tts 包),之后完全离线。
|
|
87
|
+
*/
|
|
88
|
+
const ASR_ROOT = process.env.FOLIA_ASR_ROOT || join(homedir(), '.dsh-folia', 'asr', 'v1');
|
|
89
|
+
/** 下载/就绪状态(GET /pet-chat/asr 直接回它)。 */
|
|
90
|
+
let asrState = { phase: 'idle', doneBytes: 0, totalBytes: 0, error: null };
|
|
91
|
+
/** worker 实例(懒启动,常驻)。 */
|
|
92
|
+
let asrWorker = null;
|
|
93
|
+
/** 正在进行的安装任务(并发点击 join 同一个 Promise)。 */
|
|
94
|
+
let asrInstallPromise = null;
|
|
95
|
+
|
|
96
|
+
/** 本地运行时是否已经装在盘上(不下载、只探测)。 */
|
|
97
|
+
function asrInstalledOnDisk() {
|
|
98
|
+
try {
|
|
99
|
+
return existsSync(join(ASR_ROOT, 'runtime', 'asr-worker.cjs'))
|
|
100
|
+
&& existsSync(join(ASR_ROOT, 'runtime', 'node.exe'))
|
|
101
|
+
&& existsSync(join(ASR_ROOT, 'models', 'sensevoice', 'tokens.txt'));
|
|
102
|
+
} catch { return false; }
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* 确保本地 STT 可用:装包 → 启 worker。返回 worker;失败抛错并记 asrState.failed。
|
|
107
|
+
* 幂等:并发调用共享同一个安装 Promise。
|
|
108
|
+
*/
|
|
109
|
+
function ensureLocalAsr() {
|
|
110
|
+
if (asrWorker) return Promise.resolve(asrWorker);
|
|
111
|
+
if (asrInstallPromise) return asrInstallPromise;
|
|
112
|
+
asrInstallPromise = (async () => {
|
|
113
|
+
if (!asrInstalledOnDisk()) {
|
|
114
|
+
asrState = { phase: 'downloading', doneBytes: 0, totalBytes: 0, error: null };
|
|
115
|
+
await ensureAsrInstalled(ASR_ROOT, {
|
|
116
|
+
onProgress: (p) => {
|
|
117
|
+
asrState = {
|
|
118
|
+
phase: 'downloading',
|
|
119
|
+
doneBytes: Number(p.doneBytes) || 0,
|
|
120
|
+
totalBytes: Number(p.totalBytes) || 0,
|
|
121
|
+
error: null,
|
|
122
|
+
};
|
|
123
|
+
},
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
asrState = { phase: 'loading', doneBytes: asrState.doneBytes, totalBytes: asrState.totalBytes, error: null };
|
|
127
|
+
asrWorker = startAsrWorker(ASR_ROOT);
|
|
128
|
+
asrState = { phase: 'ready', doneBytes: asrState.doneBytes, totalBytes: asrState.totalBytes, error: null };
|
|
129
|
+
return asrWorker;
|
|
130
|
+
})().catch((error) => {
|
|
131
|
+
asrWorker = null;
|
|
132
|
+
asrState = {
|
|
133
|
+
phase: 'failed',
|
|
134
|
+
doneBytes: asrState.doneBytes,
|
|
135
|
+
totalBytes: asrState.totalBytes,
|
|
136
|
+
error: String((error && error.message) || error),
|
|
137
|
+
};
|
|
138
|
+
asrInstallPromise = null;
|
|
139
|
+
throw error;
|
|
140
|
+
});
|
|
141
|
+
return asrInstallPromise;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** 本地 STT 是否已就绪(已装或已启动)—— 决定 /transcribe 走本地还是 DSH 服务。 */
|
|
145
|
+
async function localAsrReady() {
|
|
146
|
+
if (asrWorker) return true;
|
|
147
|
+
return asrInstalledOnDisk();
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* 解析 16kHz 单声道 PCM16 WAV 的时长(秒)。
|
|
152
|
+
*
|
|
153
|
+
* 为什么自己解析而不是看 `content-length`:15 秒的上限是**时长**约束,
|
|
154
|
+
* 而 44.1kHz 立体声的 15 秒会是 2.6MB —— 只看字节数会把合法的短音频挡掉。
|
|
155
|
+
* 只认 `RIFF/WAVE` + `fmt ` + `data` 三块;不是 WAV 就返回 null(调用方回 400)。
|
|
156
|
+
*/
|
|
157
|
+
export function wavSeconds(bytes) {
|
|
158
|
+
if (!bytes || bytes.byteLength < 44) return null;
|
|
159
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
160
|
+
const tag = (offset) => String.fromCharCode(bytes[offset], bytes[offset + 1], bytes[offset + 2], bytes[offset + 3]);
|
|
161
|
+
if (tag(0) !== 'RIFF' || tag(8) !== 'WAVE') return null;
|
|
162
|
+
let offset = 12;
|
|
163
|
+
let sampleRate = 0;
|
|
164
|
+
let channels = 0;
|
|
165
|
+
let bits = 0;
|
|
166
|
+
let dataBytes = 0;
|
|
167
|
+
while (offset + 8 <= bytes.byteLength) {
|
|
168
|
+
const id = tag(offset);
|
|
169
|
+
const size = view.getUint32(offset + 4, true);
|
|
170
|
+
const body = offset + 8;
|
|
171
|
+
if (id === 'fmt ' && body + 16 <= bytes.byteLength) {
|
|
172
|
+
channels = view.getUint16(body + 2, true);
|
|
173
|
+
sampleRate = view.getUint32(body + 4, true);
|
|
174
|
+
bits = view.getUint16(body + 14, true);
|
|
175
|
+
} else if (id === 'data') {
|
|
176
|
+
dataBytes = Math.min(size, bytes.byteLength - body);
|
|
177
|
+
break;
|
|
178
|
+
}
|
|
179
|
+
offset = body + size + (size % 2);
|
|
180
|
+
if (size <= 0) break;
|
|
181
|
+
}
|
|
182
|
+
if (!sampleRate || !channels || !bits || !dataBytes) return null;
|
|
183
|
+
const bytesPerFrame = channels * (bits / 8);
|
|
184
|
+
if (!bytesPerFrame) return null;
|
|
185
|
+
const seconds = dataBytes / (sampleRate * bytesPerFrame);
|
|
186
|
+
return Number.isFinite(seconds) ? seconds : null;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** base64 → Uint8Array(浏览器与 Node 都能用;Node 走 Buffer 分支)。 */
|
|
190
|
+
export function decodeBase64(text) {
|
|
191
|
+
const clean = String(text || '');
|
|
192
|
+
if (!clean) return new Uint8Array(0);
|
|
193
|
+
if (typeof Buffer !== 'undefined') return new Uint8Array(Buffer.from(clean, 'base64'));
|
|
194
|
+
const binary = atob(clean);
|
|
195
|
+
const bytes = new Uint8Array(binary.length);
|
|
196
|
+
for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
|
|
197
|
+
return bytes;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** 各 provider 的默认端点 / 默认模型(设置里 baseUrl / model 为空时用)。 */
|
|
201
|
+
const PROVIDER_DEFAULTS = {
|
|
202
|
+
// Ollama 的 OpenAI 兼容前缀是 /v1(少了它 /chat/completions 会 404)
|
|
203
|
+
ollama: { baseUrl: 'http://127.0.0.1:11434/v1', model: 'qwen2.5:7b' },
|
|
204
|
+
openai: { baseUrl: 'https://api.deepseek.com', model: 'deepseek-chat' },
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
const EMO_CODES = Object.freeze(['happy', 'calm', 'tired', 'angry']);
|
|
208
|
+
|
|
209
|
+
/** 情绪关键词兜底(模型没给合法 emotion 时用;与客户端预设台词同一套分组)。 */
|
|
210
|
+
const EMO_KEYWORDS = [
|
|
211
|
+
['happy', /哈哈|好耶|开心|太好了|喜欢|嘿嘿|✧|(^|^_^|😊|🎉/u],
|
|
212
|
+
['tired', /困|累|睡|休息|晚安|疲惫|zzz/i],
|
|
213
|
+
['angry', /生气|讨厌|烦|哼|气死|😠/u],
|
|
214
|
+
['calm', /算了|不知道|还好|一般|平静|嗯/],
|
|
215
|
+
];
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* 从一段文本里取 `{reply, emotion}`。
|
|
219
|
+
*
|
|
220
|
+
* 模型被要求输出 `{"reply":"...","emotion":"happy|calm|tired|angry"}`;
|
|
221
|
+
* 不是合法 JSON(很常见)就**整段当 reply**,情绪走关键词兜底 —— 不因为格式不对就不回答。
|
|
222
|
+
*/
|
|
223
|
+
export function parseReplyText(text) {
|
|
224
|
+
const raw = String(text ?? '');
|
|
225
|
+
const trimmed = raw.trim();
|
|
226
|
+
if (trimmed.startsWith('{')) {
|
|
227
|
+
try {
|
|
228
|
+
const doc = JSON.parse(trimmed);
|
|
229
|
+
if (doc && typeof doc.reply === 'string') {
|
|
230
|
+
return { reply: doc.reply, emotion: EMO_CODES.includes(doc.emotion) ? doc.emotion : null };
|
|
231
|
+
}
|
|
232
|
+
} catch { /* 落到下面按纯文本处理 */ }
|
|
233
|
+
}
|
|
234
|
+
return { reply: raw, emotion: null };
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** 关键词兜底(导出给测试与客户端对照)。 */
|
|
238
|
+
export function emotionFromKeywords(text) {
|
|
239
|
+
const raw = String(text ?? '');
|
|
240
|
+
for (const [code, re] of EMO_KEYWORDS) if (re.test(raw)) return code;
|
|
241
|
+
return 'calm';
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** 状态码 → 机读错误码(工单 §2.2 的 code 集合)。 */
|
|
245
|
+
function codeForStatus(status) {
|
|
246
|
+
if (status === 401 || status === 403) return { code: 'unauthorized', hint: '检查设置里的 apiKey 是否正确' };
|
|
247
|
+
if (status === 429) return { code: 'rate-limited', hint: '模型端点限流了,等一会儿再试' };
|
|
248
|
+
return { code: 'bad-request', hint: `模型端点返回 HTTP ${status}` };
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** SSE 单帧。 */
|
|
252
|
+
function sse(res, event, data) {
|
|
253
|
+
res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** 读请求体(JSON;超过上限直接拒绝)。 */
|
|
257
|
+
function readJsonBody(req, limitBytes = 16 * 1024) {
|
|
258
|
+
return new Promise((resolve, reject) => {
|
|
259
|
+
let size = 0;
|
|
260
|
+
let tooLarge = false;
|
|
261
|
+
const chunks = [];
|
|
262
|
+
req.on('data', (chunk) => {
|
|
263
|
+
size += chunk.length;
|
|
264
|
+
if (size > limitBytes) {
|
|
265
|
+
// 超限**只丢数据、不断连接**:`req.destroy()` 会让客户端拿到 ECONNRESET,
|
|
266
|
+
// 浏览器那边表现成 "fetch failed",看起来像服务器崩了 —— 其实是我们主动拒的。
|
|
267
|
+
tooLarge = true;
|
|
268
|
+
chunks.length = 0;
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
if (!tooLarge) chunks.push(chunk);
|
|
272
|
+
});
|
|
273
|
+
req.on('end', () => {
|
|
274
|
+
if (tooLarge) { reject(Object.assign(new Error('body-too-large'), { code: 'bad-request' })); return; }
|
|
275
|
+
try {
|
|
276
|
+
const text = Buffer.concat(chunks).toString('utf8');
|
|
277
|
+
resolve(text ? JSON.parse(text) : {});
|
|
278
|
+
} catch { reject(Object.assign(new Error('bad-json'), { code: 'bad-request' })); }
|
|
279
|
+
});
|
|
280
|
+
req.on('error', reject);
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** 读原始请求体(音频;超过上限直接拒绝)。 */
|
|
285
|
+
function readRawBody(req, limitBytes = 2 * 1024 * 1024) {
|
|
286
|
+
return new Promise((resolve, reject) => {
|
|
287
|
+
let size = 0;
|
|
288
|
+
let tooLarge = false;
|
|
289
|
+
const chunks = [];
|
|
290
|
+
req.on('data', (chunk) => {
|
|
291
|
+
size += chunk.length;
|
|
292
|
+
if (size > limitBytes) { tooLarge = true; chunks.length = 0; return; }
|
|
293
|
+
if (!tooLarge) chunks.push(chunk);
|
|
294
|
+
});
|
|
295
|
+
req.on('end', () => {
|
|
296
|
+
if (tooLarge) { reject(Object.assign(new Error('body-too-large'), { code: 'bad-request' })); return; }
|
|
297
|
+
resolve(new Uint8Array(Buffer.concat(chunks)));
|
|
298
|
+
});
|
|
299
|
+
req.on('error', reject);
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** 只取 IP 里的地址部分(限频键)。 */
|
|
304
|
+
function sourceOf(req) {
|
|
305
|
+
return String((req.socket && req.socket.remoteAddress) || 'unknown');
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* 把一次流式响应按 provider 解成纯文本增量。
|
|
310
|
+
*
|
|
311
|
+
* ollama:整行 JSON `{"message":{"content":"…"},"done":false}`
|
|
312
|
+
* openai:`data: {"choices":[{"delta":{"content":"…"}}]}` / `data: [DONE]`
|
|
313
|
+
* 两种都容忍空行与心跳注释(`: keep-alive`)。
|
|
314
|
+
*/
|
|
315
|
+
function* decodeStreamChunk(provider, line) {
|
|
316
|
+
const raw = String(line ?? '').trim();
|
|
317
|
+
if (!raw || raw.startsWith(':')) return;
|
|
318
|
+
const payload = raw.startsWith('data:') ? raw.slice(5).trim() : raw;
|
|
319
|
+
if (!payload || payload === '[DONE]') return;
|
|
320
|
+
let doc;
|
|
321
|
+
try { doc = JSON.parse(payload); } catch { return; }
|
|
322
|
+
if (provider === 'ollama') {
|
|
323
|
+
const piece = doc && doc.message && typeof doc.message.content === 'string' ? doc.message.content : '';
|
|
324
|
+
if (piece) yield piece;
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
const choice = doc && Array.isArray(doc.choices) ? doc.choices[0] : null;
|
|
328
|
+
const piece = choice && choice.delta && typeof choice.delta.content === 'string' ? choice.delta.content : '';
|
|
329
|
+
if (piece) yield piece;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
export function registerPetChatRoutes(webServer, c) {
|
|
333
|
+
const { disposers, base: BASE, log, readSettings, speechToText } = c;
|
|
334
|
+
|
|
335
|
+
/** 宿主侧录音器:**必须在这里实例化** —— 只 import 不 new,/record 会抛
|
|
336
|
+
* ReferenceError: voiceRecorder is not defined(P6 实锤)。 */
|
|
337
|
+
const voiceRecorder = createVoiceRecorder({
|
|
338
|
+
resolveFfmpeg: defaultResolveFfmpeg,
|
|
339
|
+
runFfmpeg: defaultRunFfmpeg,
|
|
340
|
+
});
|
|
341
|
+
|
|
342
|
+
/** 当前进程内的会话记忆(重启即忘;`/reset` 清空)。 */
|
|
343
|
+
let memory = [];
|
|
344
|
+
/** 轮次计数(摘要触发用)与最近一次摘要时间。 */
|
|
345
|
+
let turnCount = 0;
|
|
346
|
+
let lastMemoryAt = 0;
|
|
347
|
+
/** 同一来源的最近一次请求时间(限频)。 */
|
|
348
|
+
const lastAt = new Map();
|
|
349
|
+
/** 转写限频(1 次 / 2 秒):同一来源一张表。 */
|
|
350
|
+
const asrLastAt = new Map();
|
|
351
|
+
/** 最近一次失败原因(`/state` 里回给界面)。 */
|
|
352
|
+
let lastError = null;
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* 面板保存的覆盖层(`<DSH_FOLIA_HOME>/pet-chat/settings.json`)。
|
|
356
|
+
*
|
|
357
|
+
* 为什么不用 DSH 的设置服务:插件这边只拿到了 `readSettings`(只读),没有写入口;
|
|
358
|
+
* 桌宠面板又必须能改(开启对话 / 换模型 / 填 key 都在这里)。所以沿用 `/pets/config`
|
|
359
|
+
* 的做法,用一个插件自己的配置文件当**覆盖层**:
|
|
360
|
+
* · 读:schema 默认值 → DSH 设置 → 本文件(后者优先)
|
|
361
|
+
* · 写:只写本文件,不动 DSH 的设置档
|
|
362
|
+
* 好处是面板保存立刻生效、且插件卸载时删掉文件就回到 DSH 设置。
|
|
363
|
+
*/
|
|
364
|
+
function overlayPath() {
|
|
365
|
+
const base = process.env.DSH_FOLIA_HOME || join(homedir(), '.dsh-folia');
|
|
366
|
+
return join(base, 'pet-chat', 'settings.json');
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function readOverlay() {
|
|
370
|
+
try {
|
|
371
|
+
const file = overlayPath();
|
|
372
|
+
if (!existsSync(file)) return null;
|
|
373
|
+
const doc = JSON.parse(readFileSync(file, 'utf8'));
|
|
374
|
+
return doc && typeof doc === 'object' ? doc : null;
|
|
375
|
+
} catch { return null; }
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
function writeOverlay(patch) {
|
|
379
|
+
const file = overlayPath();
|
|
380
|
+
const current = readOverlay() || {};
|
|
381
|
+
const next = { ...current, ...patch };
|
|
382
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
383
|
+
writeFileSync(file, JSON.stringify(next, null, 2));
|
|
384
|
+
return next;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/** 读当前 petChat 配置(每次现读:设置面板改完立刻生效,不用重启)。 */
|
|
388
|
+
function readPetChat() {
|
|
389
|
+
let settings = null;
|
|
390
|
+
try { settings = readSettings(); } catch (error) {
|
|
391
|
+
// 读设置失败不能让整条链路炸:当作默认(关)
|
|
392
|
+
log('[pet-chat] 读设置失败:' + String((error && error.message) || error));
|
|
393
|
+
}
|
|
394
|
+
const schemaRaw = settings && typeof settings === 'object' && settings.petChat && typeof settings.petChat === 'object'
|
|
395
|
+
? settings.petChat : {};
|
|
396
|
+
// 旧键映射只写一处:settings-schema 的 readPetChat 同时负责"默认值 + 迁移"
|
|
397
|
+
const normalized = normalizePetChat({ ...schemaRaw, ...(readOverlay() || {}) });
|
|
398
|
+
const provider = normalized.provider === 'openai' ? 'openai' : 'ollama';
|
|
399
|
+
const defaults = PROVIDER_DEFAULTS[provider];
|
|
400
|
+
const baseUrl = typeof normalized.baseUrl === 'string' && normalized.baseUrl.trim() ? normalized.baseUrl.trim() : defaults.baseUrl;
|
|
401
|
+
return {
|
|
402
|
+
enabled: normalized.enabled === true,
|
|
403
|
+
provider,
|
|
404
|
+
baseUrl: baseUrl.replace(/\/+$/, ''),
|
|
405
|
+
apiKey: normalized.apiKey,
|
|
406
|
+
model: typeof normalized.model === 'string' && normalized.model.trim() ? normalized.model.trim() : defaults.model,
|
|
407
|
+
// v0.1 设置收敛:名字两项 + 音色两项 + 唤醒三项,其余(轮数/字数)是代码常量
|
|
408
|
+
petName: normalized.petName,
|
|
409
|
+
ownerName: normalized.ownerName,
|
|
410
|
+
voice: normalized.voice,
|
|
411
|
+
wake: normalized.wake,
|
|
412
|
+
// 记忆常开(零配置):设置里没有开关
|
|
413
|
+
memoryEnabled: true,
|
|
414
|
+
// 实现细节:不再暴露给用户,也不再从设置里读
|
|
415
|
+
maxTurns: DEFAULT_MAX_TURNS,
|
|
416
|
+
maxChars: DEFAULT_MAX_CHARS,
|
|
417
|
+
// 内部旋钮:不进 UI,但保留可配置(测试与排障用)
|
|
418
|
+
memoryEveryTurns: (() => {
|
|
419
|
+
const raw = Number((readOverlay() || {}).memoryEveryTurns ?? schemaRaw.memoryEveryTurns);
|
|
420
|
+
return Number.isFinite(raw) && raw > 0 ? Math.min(50, raw) : DEFAULT_MEMORY_EVERY_TURNS;
|
|
421
|
+
})(),
|
|
422
|
+
};
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/** 组装请求体(两种协议各一份;都只发到配置里的端点)。 */
|
|
426
|
+
function buildRequest(config, text) {
|
|
427
|
+
// v0.1:人设不再是一长串设置,只有"名字 / 主人称呼"两项;风格走内置文案
|
|
428
|
+
const petName = config.petName || 'Folia';
|
|
429
|
+
const ownerName = config.ownerName ? `,称呼用户为「${config.ownerName}」` : '';
|
|
430
|
+
let system = `你是${petName}${ownerName},元气、短句、偶尔颜文字、不说教;`
|
|
431
|
+
+ '你的特点:喜欢壁纸和游戏,被夸会害羞。'
|
|
432
|
+
+ `用中文口语回答,最多 ${config.maxChars} 字,不用 Markdown。`
|
|
433
|
+
+ '直接说人话,不要输出 JSON、不要加前缀、不要解释格式。';
|
|
434
|
+
// 工单 A5⑤ 的判据是「第 9 轮只带最近 8 条」⇒ 上限按**条**算(一问一答 = 2 条)
|
|
435
|
+
// B3:把长期偏好注入 system prompt(≤80 字;记忆为空时这一行为空)
|
|
436
|
+
const memoryLine = config.memoryEnabled ? memoryPromptLine(readMemory()) : '';
|
|
437
|
+
if (memoryLine) system += '\n' + memoryLine;
|
|
438
|
+
const history = memory.slice(-config.maxTurns);
|
|
439
|
+
const headers = { 'content-type': 'application/json' };
|
|
440
|
+
if (config.provider === 'openai') {
|
|
441
|
+
if (config.apiKey) headers.authorization = `Bearer ${config.apiKey}`;
|
|
442
|
+
return {
|
|
443
|
+
url: `${config.baseUrl}/chat/completions`,
|
|
444
|
+
body: {
|
|
445
|
+
model: config.model,
|
|
446
|
+
stream: true,
|
|
447
|
+
temperature: 0.8,
|
|
448
|
+
messages: [{ role: 'system', content: system }, ...history, { role: 'user', content: text }],
|
|
449
|
+
},
|
|
450
|
+
headers,
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
return {
|
|
454
|
+
url: `${config.baseUrl}/api/chat`,
|
|
455
|
+
body: {
|
|
456
|
+
model: config.model,
|
|
457
|
+
stream: true,
|
|
458
|
+
messages: [{ role: 'system', content: system }, ...history, { role: 'user', content: text }],
|
|
459
|
+
},
|
|
460
|
+
headers,
|
|
461
|
+
};
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/** GET /pet-chat/state */
|
|
465
|
+
async function handleState(res) {
|
|
466
|
+
const config = readPetChat();
|
|
467
|
+
let reachable = false;
|
|
468
|
+
if (config.enabled) {
|
|
469
|
+
const controller = new AbortController();
|
|
470
|
+
const timer = setTimeout(() => controller.abort(), 1500);
|
|
471
|
+
try {
|
|
472
|
+
const probe = config.provider === 'ollama' ? `${config.baseUrl}/api/tags` : `${config.baseUrl}/models`;
|
|
473
|
+
const headers = {};
|
|
474
|
+
if (config.provider === 'openai' && config.apiKey) headers.authorization = `Bearer ${config.apiKey}`;
|
|
475
|
+
const response = await fetch(probe, { headers, signal: controller.signal });
|
|
476
|
+
reachable = response.ok;
|
|
477
|
+
if (!response.ok) lastError = codeForStatus(response.status).code;
|
|
478
|
+
} catch {
|
|
479
|
+
reachable = false;
|
|
480
|
+
lastError = 'unreachable';
|
|
481
|
+
} finally {
|
|
482
|
+
clearTimeout(timer);
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
486
|
+
res.end(JSON.stringify({
|
|
487
|
+
ok: true,
|
|
488
|
+
enabled: config.enabled,
|
|
489
|
+
provider: config.provider,
|
|
490
|
+
model: config.model,
|
|
491
|
+
reachable,
|
|
492
|
+
lastError,
|
|
493
|
+
// v0.1:语音输入开关随设置收敛去掉(能力由 DSH 决定);语音/名字照旧回给客户端
|
|
494
|
+
petName: config.petName,
|
|
495
|
+
ownerName: config.ownerName,
|
|
496
|
+
voice: config.voice,
|
|
497
|
+
memoryEnabled: config.memoryEnabled,
|
|
498
|
+
asrProvider: ASR_PROVIDER_ID,
|
|
499
|
+
}));
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/** GET /pet-chat/models */
|
|
503
|
+
async function handleModels(res) {
|
|
504
|
+
const config = readPetChat();
|
|
505
|
+
const send = (payload) => {
|
|
506
|
+
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
507
|
+
res.end(JSON.stringify(payload));
|
|
508
|
+
};
|
|
509
|
+
if (config.provider === 'openai') {
|
|
510
|
+
send({ ok: true, provider: 'openai', models: [], hint: 'OpenAI 兼容端点不提供模型列表,直接在设置里填模型名' });
|
|
511
|
+
return;
|
|
512
|
+
}
|
|
513
|
+
const controller = new AbortController();
|
|
514
|
+
const timer = setTimeout(() => controller.abort(), 4000);
|
|
515
|
+
try {
|
|
516
|
+
const response = await fetch(`${config.baseUrl}/api/tags`, { signal: controller.signal });
|
|
517
|
+
if (!response.ok) { send({ ok: false, provider: 'ollama', models: [], hint: `HTTP ${response.status}` }); return; }
|
|
518
|
+
const doc = await response.json();
|
|
519
|
+
const models = (doc && Array.isArray(doc.models) ? doc.models : [])
|
|
520
|
+
.map((item) => (item && typeof item.name === 'string' ? item.name : null))
|
|
521
|
+
.filter(Boolean);
|
|
522
|
+
send({ ok: true, provider: 'ollama', models });
|
|
523
|
+
} catch {
|
|
524
|
+
send({ ok: false, provider: 'ollama', models: [], hint: '连不上本机 Ollama(127.0.0.1:11434)' });
|
|
525
|
+
} finally {
|
|
526
|
+
clearTimeout(timer);
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/** POST /pet-chat/chat(SSE) */
|
|
531
|
+
async function handleChat(req, res) {
|
|
532
|
+
const ip = sourceOf(req);
|
|
533
|
+
const now = Date.now();
|
|
534
|
+
const prev = lastAt.get(ip) || 0;
|
|
535
|
+
res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
|
|
536
|
+
res.setHeader('Cache-Control', 'no-cache');
|
|
537
|
+
res.setHeader('Connection', 'keep-alive');
|
|
538
|
+
res.setHeader('X-Accel-Buffering', 'no');
|
|
539
|
+
const fail = (code, hint) => {
|
|
540
|
+
lastError = code;
|
|
541
|
+
sse(res, 'error', { code, hint });
|
|
542
|
+
res.end();
|
|
543
|
+
};
|
|
544
|
+
|
|
545
|
+
if (now - prev < RATE_LIMIT_MS) { fail('rate-limited', '一秒一次,慢点~'); return; }
|
|
546
|
+
lastAt.set(ip, now);
|
|
547
|
+
|
|
548
|
+
let body;
|
|
549
|
+
try { body = await readJsonBody(req); } catch { fail('bad-request', '请求体不是合法 JSON'); return; }
|
|
550
|
+
const text = typeof body.text === 'string' ? body.text.trim() : '';
|
|
551
|
+
if (!text) { fail('bad-request', '说点什么吧'); return; }
|
|
552
|
+
if ([...text].length > MAX_INPUT_CHARS) { fail('bad-request', `一次最多 ${MAX_INPUT_CHARS} 字`); return; }
|
|
553
|
+
|
|
554
|
+
const config = readPetChat();
|
|
555
|
+
if (!config.enabled) { fail('no-model', '先在设置里打开桌宠对话并填一个模型'); return; }
|
|
556
|
+
|
|
557
|
+
/**
|
|
558
|
+
* 语音/打字指令:**说"别说了"就静默**(到次日 0 点),说"可以说话了"就恢复。
|
|
559
|
+
* 这是「零配置」里用户唯一的控制方式(追加决定 2),所以在这里拦一道,
|
|
560
|
+
* 命中就不调模型(省 token,也让响应立刻生效)。
|
|
561
|
+
*/
|
|
562
|
+
const command = parseSilenceCommand(text);
|
|
563
|
+
if (command === 'silence') {
|
|
564
|
+
enterSilence();
|
|
565
|
+
res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
|
|
566
|
+
sse(res, 'delta', { t: '好,那我安静一会儿。' });
|
|
567
|
+
sse(res, 'done', { emotion: 'calm', command: 'silence' });
|
|
568
|
+
res.end();
|
|
569
|
+
return;
|
|
570
|
+
}
|
|
571
|
+
if (command === 'resume') {
|
|
572
|
+
clearSilence();
|
|
573
|
+
res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
|
|
574
|
+
sse(res, 'delta', { t: '好,我回来了。' });
|
|
575
|
+
sse(res, 'done', { emotion: 'happy', command: 'resume' });
|
|
576
|
+
res.end();
|
|
577
|
+
return;
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
if (config.provider === 'openai' && !config.apiKey) {
|
|
581
|
+
fail('no-model', '填 DeepSeek API Key 即可对话(也可改用本机 Ollama,检测到 127.0.0.1:11434 时会提示)');
|
|
582
|
+
return;
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
const request = buildRequest(config, text);
|
|
586
|
+
const controller = new AbortController();
|
|
587
|
+
const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
|
|
588
|
+
let finished = false;
|
|
589
|
+
const done = (emotion, usage) => {
|
|
590
|
+
if (finished) return;
|
|
591
|
+
finished = true;
|
|
592
|
+
sse(res, 'done', { emotion, usage: usage || null });
|
|
593
|
+
res.end();
|
|
594
|
+
};
|
|
595
|
+
|
|
596
|
+
try {
|
|
597
|
+
const response = await fetch(request.url, {
|
|
598
|
+
method: 'POST',
|
|
599
|
+
headers: request.headers,
|
|
600
|
+
body: JSON.stringify(request.body),
|
|
601
|
+
signal: controller.signal,
|
|
602
|
+
});
|
|
603
|
+
if (!response.ok) {
|
|
604
|
+
const mapped = codeForStatus(response.status);
|
|
605
|
+
fail(mapped.code, mapped.hint);
|
|
606
|
+
return;
|
|
607
|
+
}
|
|
608
|
+
const reader = response.body.getReader();
|
|
609
|
+
const decoder = new TextDecoder();
|
|
610
|
+
let buffer = '';
|
|
611
|
+
let full = '';
|
|
612
|
+
for (;;) {
|
|
613
|
+
// eslint-disable-next-line no-await-in-loop -- 流式读取必须逐块等
|
|
614
|
+
const { value, done: ended } = await reader.read();
|
|
615
|
+
if (ended) break;
|
|
616
|
+
buffer += decoder.decode(value, { stream: true });
|
|
617
|
+
const lines = buffer.split('\n');
|
|
618
|
+
buffer = lines.pop() ?? '';
|
|
619
|
+
for (const line of lines) {
|
|
620
|
+
for (const piece of decodeStreamChunk(config.provider, line)) {
|
|
621
|
+
// 回复长度上限(工单 A5⑥):超了就**在流里截断**,不把超长内容推给气泡,
|
|
622
|
+
// 也不假装没发生 —— 截断处就是 done,客户端拿到的长度恒 ≤ maxChars。
|
|
623
|
+
const room = config.maxChars - full.length;
|
|
624
|
+
if (room <= 0) break;
|
|
625
|
+
const chunk = piece.length > room ? piece.slice(0, room) : piece;
|
|
626
|
+
full += chunk;
|
|
627
|
+
sse(res, 'delta', { t: chunk });
|
|
628
|
+
if (full.length >= config.maxChars) break;
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
const parsed = parseReplyText(full);
|
|
633
|
+
const emotion = parsed.emotion || emotionFromKeywords(parsed.reply);
|
|
634
|
+
// B2①:用户显式说「记住…」⇒ 立刻写记忆(只存结论)
|
|
635
|
+
if (config.memoryEnabled) {
|
|
636
|
+
const explicit = parseExplicitMemory(text);
|
|
637
|
+
if (explicit) rememberExplicit(readMemory(), explicit);
|
|
638
|
+
}
|
|
639
|
+
memory.push({ role: 'user', content: text });
|
|
640
|
+
memory.push({ role: 'assistant', content: parsed.reply });
|
|
641
|
+
turnCount += 1;
|
|
642
|
+
// B2②:每 N 轮让模型吐一次摘要 ⇒ 合并去重(不覆盖显式项)
|
|
643
|
+
if (config.memoryEnabled && turnCount % config.memoryEveryTurns === 0) {
|
|
644
|
+
const merged = await summarizeMemory(config, memory.slice(-config.maxTurns));
|
|
645
|
+
if (merged) lastMemoryAt = Date.now();
|
|
646
|
+
}
|
|
647
|
+
if (memory.length > MAX_MEMORY_TURNS * 2) memory = memory.slice(-MAX_MEMORY_TURNS * 2);
|
|
648
|
+
done(emotion, { chars: parsed.reply.length });
|
|
649
|
+
} catch (error) {
|
|
650
|
+
if (error && error.name === 'AbortError') fail('timeout', '模型 20 秒没回应,再试一次');
|
|
651
|
+
else fail('bad-request', '连不上模型端点,检查设置里的地址');
|
|
652
|
+
} finally {
|
|
653
|
+
clearTimeout(timer);
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
/**
|
|
658
|
+
* B2②:让模型对最近几轮做一次**偏好提炼**(非流式,独立请求)。
|
|
659
|
+
* 失败一律吞掉(记忆是加分项,不能因为它把聊天弄挂)。
|
|
660
|
+
*/
|
|
661
|
+
async function summarizeMemory(config, history) {
|
|
662
|
+
try {
|
|
663
|
+
const controller = new AbortController();
|
|
664
|
+
const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
|
|
665
|
+
const headers = { 'content-type': 'application/json' };
|
|
666
|
+
if (config.provider === 'openai' && config.apiKey) headers.authorization = `Bearer ${config.apiKey}`;
|
|
667
|
+
const url = config.provider === 'ollama' ? `${config.baseUrl}/api/chat` : `${config.baseUrl}/chat/completions`;
|
|
668
|
+
const body = {
|
|
669
|
+
model: config.model,
|
|
670
|
+
stream: false,
|
|
671
|
+
messages: [{ role: 'system', content: MEMORY_SUMMARY_PROMPT }, ...history],
|
|
672
|
+
};
|
|
673
|
+
const response = await fetch(url, { method: 'POST', headers, body: JSON.stringify(body), signal: controller.signal });
|
|
674
|
+
clearTimeout(timer);
|
|
675
|
+
if (!response.ok) return null;
|
|
676
|
+
const doc = await response.json();
|
|
677
|
+
const content = config.provider === 'ollama'
|
|
678
|
+
? (doc && doc.message && doc.message.content)
|
|
679
|
+
: (doc && doc.choices && doc.choices[0] && doc.choices[0].message && doc.choices[0].message.content);
|
|
680
|
+
if (typeof content !== 'string') return null;
|
|
681
|
+
const jsonStart = content.indexOf('{');
|
|
682
|
+
const jsonEnd = content.lastIndexOf('}');
|
|
683
|
+
if (jsonStart < 0 || jsonEnd <= jsonStart) return null;
|
|
684
|
+
const summary = JSON.parse(content.slice(jsonStart, jsonEnd + 1));
|
|
685
|
+
return mergeSummary(readMemory(), summary);
|
|
686
|
+
} catch {
|
|
687
|
+
return null;
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
|
|
692
|
+
/**
|
|
693
|
+
* POST /pet-chat/transcribe —— 把一段 WAV 交给 DSH 宿主的转写服务。
|
|
694
|
+
*
|
|
695
|
+
* 为什么不在插件里带模型:DSH 已经有 `ctx.speechToText`(provider 自己下载并校验模型)。
|
|
696
|
+
* 插件这边只做「收音频 → 校验 → 转发 → 回文本」四件事,序列化与推理都不碰。
|
|
697
|
+
*
|
|
698
|
+
* 返回(**一律 200**,除参数不合法):
|
|
699
|
+
* · 成功 `{ ok:true, text, audioSeconds, inferenceSeconds }`
|
|
700
|
+
* · 未就绪 `{ ok:false, code:'asr-not-ready', hint:'请在 DSH 设置启用语音输入(需下载模型)' }`
|
|
701
|
+
* · 超时取消 `{ ok:false, code:'asr-timeout' }`
|
|
702
|
+
* 参数不合法(超长/超大/不是 WAV)走 400 `bad-request` —— 那是客户端 bug,不是环境问题。
|
|
703
|
+
*/
|
|
704
|
+
async function handleTranscribe(req, res) {
|
|
705
|
+
const ip = sourceOf(req);
|
|
706
|
+
const send = (payload, status = 200) => {
|
|
707
|
+
res.statusCode = status;
|
|
708
|
+
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
709
|
+
res.end(JSON.stringify(payload));
|
|
710
|
+
};
|
|
711
|
+
|
|
712
|
+
// 两种入参:JSON `{audio: base64, language}` 或原始 WAV 体(content-type: audio/wav)
|
|
713
|
+
const contentType = String(req.headers['content-type'] || '').toLowerCase();
|
|
714
|
+
let audio;
|
|
715
|
+
let language = 'zh';
|
|
716
|
+
try {
|
|
717
|
+
if (contentType.includes('audio/')) {
|
|
718
|
+
audio = new Uint8Array(await readRawBody(req, ASR_MAX_BYTES + 1));
|
|
719
|
+
} else {
|
|
720
|
+
const body = await readJsonBody(req, ASR_MAX_BYTES + 4096);
|
|
721
|
+
if (typeof body.audio === 'string') audio = decodeBase64(body.audio);
|
|
722
|
+
else if (Array.isArray(body.audio)) audio = Uint8Array.from(body.audio);
|
|
723
|
+
else audio = new Uint8Array(0);
|
|
724
|
+
if (typeof body.language === 'string' && body.language) language = body.language.slice(0, 8);
|
|
725
|
+
}
|
|
726
|
+
} catch {
|
|
727
|
+
send({ ok: false, code: 'bad-request', hint: '请求体不是合法的 JSON / 音频' }, 400);
|
|
728
|
+
return;
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
if (!audio || !audio.byteLength) { send({ ok: false, code: 'bad-request', hint: '音频为空' }, 400); return; }
|
|
732
|
+
if (audio.byteLength > ASR_MAX_BYTES) { send({ ok: false, code: 'bad-request', hint: '音频超过 2MB' }, 400); return; }
|
|
733
|
+
const seconds = wavSeconds(audio);
|
|
734
|
+
if (seconds === null) { send({ ok: false, code: 'bad-request', hint: '只接受 16kHz 单声道 PCM16 WAV' }, 400); return; }
|
|
735
|
+
if (seconds > ASR_MAX_SECONDS) {
|
|
736
|
+
send({ ok: false, code: 'bad-request', hint: `单段最多 ${ASR_MAX_SECONDS} 秒(这段 ${seconds.toFixed(1)} 秒)` }, 400);
|
|
737
|
+
return;
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
// 参数都合法了才计入限频:坏请求不占配额
|
|
741
|
+
const lastAtMs = asrLastAt.get(ip) || 0;
|
|
742
|
+
const nowMs = Date.now();
|
|
743
|
+
if (nowMs - lastAtMs < ASR_RATE_LIMIT_MS) {
|
|
744
|
+
send({ ok: false, code: 'rate-limited', hint: '2 秒内最多转写一次' });
|
|
745
|
+
return;
|
|
746
|
+
}
|
|
747
|
+
asrLastAt.set(ip, nowMs);
|
|
748
|
+
|
|
749
|
+
// ① 服务可能压根没装(用户没启用「语音输入」实验特性)
|
|
750
|
+
// 本地 STT 优先:收到的是 WAV 字节 ⇒ 落临时文件交给 worker 识别
|
|
751
|
+
if (await localAsrReady()) {
|
|
752
|
+
try {
|
|
753
|
+
const dir = mkdtempSync(join(tmpdir(), 'folia-asr-'));
|
|
754
|
+
const wavPath = join(dir, 'input.wav');
|
|
755
|
+
writeFileSync(wavPath, Buffer.from(audio));
|
|
756
|
+
const worker = await ensureLocalAsr();
|
|
757
|
+
const spoken = await worker.request(wavPath, ASR_TIMEOUT_MS);
|
|
758
|
+
try { rmSync(dir, { recursive: true, force: true }); } catch { /* ignore */ }
|
|
759
|
+
if (!spoken || !spoken.ok) { send({ ok: false, code: 'asr-failed', hint: '识别失败,再试一次' }, 502); return; }
|
|
760
|
+
const text = String(spoken.text || '').trim();
|
|
761
|
+
if (!text) { send({ ok: false, code: 'no-speech', hint: '没听清,再说一次' }, 422); return; }
|
|
762
|
+
send({ ok: true, text, ms: spoken.ms, seconds });
|
|
763
|
+
return;
|
|
764
|
+
} catch {
|
|
765
|
+
// 落到下面的 DSH 服务路径
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
const service = speechToText;
|
|
769
|
+
if (!service || typeof service.snapshot !== 'function' || typeof service.transcribe !== 'function') {
|
|
770
|
+
send({ ok: false, code: 'asr-not-ready', hint: ASR_NOT_READY_HINT });
|
|
771
|
+
return;
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
// ② 服务装了,但 provider 没就绪(没下载 / 正在下 / 加载失败)——用快照判断,不要靠 try/catch 猜
|
|
775
|
+
let phase = 'missing';
|
|
776
|
+
try {
|
|
777
|
+
const snapshot = service.snapshot();
|
|
778
|
+
const provider = (snapshot && Array.isArray(snapshot.providers) ? snapshot.providers : [])
|
|
779
|
+
.find((item) => item && item.id === ASR_PROVIDER_ID);
|
|
780
|
+
phase = provider && provider.preparation ? provider.preparation.phase : 'missing';
|
|
781
|
+
} catch (error) {
|
|
782
|
+
log('[pet-chat] speechToText.snapshot 失败:' + String((error && error.message) || error));
|
|
783
|
+
phase = 'missing';
|
|
784
|
+
}
|
|
785
|
+
if (phase !== 'ready') {
|
|
786
|
+
send({
|
|
787
|
+
ok: false,
|
|
788
|
+
code: 'asr-not-ready',
|
|
789
|
+
hint: phase === 'missing'
|
|
790
|
+
? ASR_NOT_READY_HINT
|
|
791
|
+
: `${ASR_NOT_READY_HINT}(当前状态:${phase})`,
|
|
792
|
+
phase,
|
|
793
|
+
});
|
|
794
|
+
return;
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
// ③ 就绪:resolve 出 provider-pinned spec,再执行
|
|
798
|
+
let spec;
|
|
799
|
+
try {
|
|
800
|
+
spec = service.resolve({ audio, language: ASR_LANGUAGE, providerId: ASR_PROVIDER_ID });
|
|
801
|
+
} catch (error) {
|
|
802
|
+
send({ ok: false, code: 'asr-not-ready', hint: ASR_NOT_READY_HINT });
|
|
803
|
+
log('[pet-chat] speechToText.resolve 失败:' + String((error && error.message) || error));
|
|
804
|
+
return;
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
const controller = new AbortController();
|
|
808
|
+
const timer = setTimeout(() => controller.abort(), ASR_TIMEOUT_MS);
|
|
809
|
+
try {
|
|
810
|
+
const transcript = await service.transcribe(spec, controller.signal);
|
|
811
|
+
send({
|
|
812
|
+
ok: true,
|
|
813
|
+
text: String((transcript && transcript.text) || ''),
|
|
814
|
+
audioSeconds: Number((transcript && transcript.audioSeconds) || seconds),
|
|
815
|
+
inferenceSeconds: Number((transcript && transcript.inferenceSeconds) || 0),
|
|
816
|
+
});
|
|
817
|
+
} catch (error) {
|
|
818
|
+
const aborted = controller.signal.aborted || (error && error.name === 'AbortError');
|
|
819
|
+
send(aborted
|
|
820
|
+
? { ok: false, code: 'asr-timeout', hint: '转写超时,再试一次' }
|
|
821
|
+
: { ok: false, code: 'asr-failed', hint: '转写失败,可以改用打字' });
|
|
822
|
+
} finally {
|
|
823
|
+
clearTimeout(timer);
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
/** Uint8Array → base64(Node 与 Worker 都能用)。 */
|
|
828
|
+
function toBase64(bytes) {
|
|
829
|
+
if (!bytes || !bytes.byteLength) return '';
|
|
830
|
+
if (typeof Buffer !== 'undefined') return Buffer.from(bytes).toString('base64');
|
|
831
|
+
let binary = '';
|
|
832
|
+
for (let i = 0; i < bytes.length; i += 1) binary += String.fromCharCode(bytes[i]);
|
|
833
|
+
return btoa(binary);
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
/**
|
|
837
|
+
* 设置面板用的读写接口。
|
|
838
|
+
*
|
|
839
|
+
* GET /pet-chat/config 回完整配置(apiKey 只回掩码 + hasApiKey)
|
|
840
|
+
* POST /pet-chat/config 保存(写覆盖层;provider=ollama 时强制默认地址、清空 key)
|
|
841
|
+
* POST /pet-chat/test 真连一次 provider,失败给具体原因(401/402/超时/地址错)
|
|
842
|
+
* DELETE /pet-chat/memory 只清记忆,不动对话与设置
|
|
843
|
+
*/
|
|
844
|
+
/**
|
|
845
|
+
* POST /pet-chat/record —— 宿主侧录一段,然后走现有 speechToText 转写。
|
|
846
|
+
* 前端不再碰 getUserMedia(Electron 权限只放行 clipboard/notifications)。
|
|
847
|
+
*/
|
|
848
|
+
async function handleRecord(req, res) {
|
|
849
|
+
let body = {};
|
|
850
|
+
try { body = await readJsonBody(req); } catch { body = {}; }
|
|
851
|
+
const result = await voiceRecorder.record({
|
|
852
|
+
maxMs: Number(body.maxMs) || undefined,
|
|
853
|
+
silenceDb: body.silenceDb === undefined ? undefined : Number(body.silenceDb),
|
|
854
|
+
silenceMs: Number(body.silenceMs) || undefined,
|
|
855
|
+
});
|
|
856
|
+
const send = (payload, status = 200) => {
|
|
857
|
+
res.statusCode = status;
|
|
858
|
+
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
859
|
+
res.end(JSON.stringify(payload));
|
|
860
|
+
};
|
|
861
|
+
if (!result.ok) {
|
|
862
|
+
const hints = {
|
|
863
863
|
'no-device': '没找到可用麦克风(检查系统录音设备或是否被其它程序占用)',
|
|
864
|
-
'unsupported-platform': '这个系统不支持桌面录音,用浏览器打开 DSH 才能语音',
|
|
865
|
-
'ffmpeg-missing': '缺少 ffmpeg,无法录音',
|
|
866
|
-
timeout: '录音超时,再说一次',
|
|
867
|
-
'no-speech': '没听到声音,再说一次或直接打字',
|
|
868
|
-
};
|
|
869
|
-
send({ ok: false, code: result.code, hint: hints[result.code] || '录音失败' }, result.code === 'ffmpeg-missing' ? 503 : 422);
|
|
870
|
-
return;
|
|
871
|
-
}
|
|
872
|
-
// ── 转写:本地 SenseVoice 优先;没装/没下好 ⇒ asr-not-ready,由客户端触发下载 ──
|
|
873
|
-
try {
|
|
874
|
-
const worker = await ensureLocalAsr();
|
|
875
|
-
const spoken = await worker.request(result.audioPath, ASR_TIMEOUT_MS);
|
|
876
|
-
if (!spoken || !spoken.ok) {
|
|
877
|
-
send({ ok: false, code: 'asr-failed', hint: '识别失败,再试一次或直接打字' }, 502);
|
|
878
|
-
return;
|
|
879
|
-
}
|
|
880
|
-
const text = String(spoken.text || '').trim();
|
|
881
|
-
if (!text) { send({ ok: false, code: 'no-speech', hint: '没听清,再说一次' }, 422); return; }
|
|
882
|
-
send({ ok: true, text, ms: spoken.ms, audioSeconds: result.audioSeconds });
|
|
883
|
-
} catch (error) {
|
|
884
|
-
const message = String((error && error.message) || error);
|
|
885
|
-
const notReady = /manifest|下载|ENOENT|缺少/.test(message) || asrState.phase !== 'ready';
|
|
886
|
-
if (notReady) {
|
|
887
|
-
send({ ok: false, code: 'asr-not-ready', hint: ASR_NOT_READY_HINT }, 422);
|
|
888
|
-
} else {
|
|
889
|
-
send({ ok: false, code: 'asr-failed', hint: '转写失败,重试或直接打字' }, 502);
|
|
890
|
-
}
|
|
891
|
-
} finally {
|
|
892
|
-
try {
|
|
893
|
-
const { rmSync } = await import('node:fs');
|
|
894
|
-
if (result.dir) rmSync(result.dir, { recursive: true, force: true });
|
|
895
|
-
} catch { /* ignore */ }
|
|
896
|
-
}
|
|
897
|
-
}
|
|
898
|
-
|
|
899
|
-
/**
|
|
900
|
-
* GET /pet-chat/asr —— 本地 STT 运行时的状态 / 下载进度。
|
|
901
|
-
* phase: idle | downloading | loading | ready | failed
|
|
902
|
-
* downloading 时带 doneBytes / totalBytes(客户端用它显示"下载中 x%")。
|
|
903
|
-
*/
|
|
904
|
-
function handleAsrStatus(res) {
|
|
905
|
-
const send = (payload, status = 200) => {
|
|
906
|
-
res.statusCode = status;
|
|
907
|
-
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
908
|
-
res.end(JSON.stringify(payload));
|
|
909
|
-
};
|
|
910
|
-
if (!asrWorker && asrState.phase === 'idle' && asrInstalledOnDisk()) {
|
|
911
|
-
asrState = { ...asrState, phase: 'ready' };
|
|
912
|
-
}
|
|
913
|
-
const total = Number(asrState.totalBytes) || 0;
|
|
914
|
-
const done = Number(asrState.doneBytes) || 0;
|
|
915
|
-
send({
|
|
916
|
-
ok: true,
|
|
917
|
-
available: true,
|
|
918
|
-
engine: 'local-sensevoice',
|
|
919
|
-
providerId: ASR_PROVIDER_ID,
|
|
920
|
-
phase: asrState.phase,
|
|
921
|
-
completedBytes: done,
|
|
922
|
-
totalBytes: total,
|
|
923
|
-
percent: total > 0 ? Math.min(100, Math.round((done / total) * 100)) : null,
|
|
924
|
-
ready: asrState.phase === 'ready',
|
|
925
|
-
message: asrState.error || null,
|
|
926
|
-
});
|
|
927
|
-
}
|
|
928
|
-
|
|
929
|
-
/**
|
|
930
|
-
* POST /pet-chat/asr —— 触发本地运行时下载(幂等;已在下载会 join 同一个任务)。
|
|
931
|
-
* 用户装完插件点桌宠说话就会走这里,不需要去 DSH 设置里找任何开关。
|
|
932
|
-
*/
|
|
933
|
-
function handleAsrPrepare(res) {
|
|
934
|
-
const send = (payload, status = 200) => {
|
|
935
|
-
res.statusCode = status;
|
|
936
|
-
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
937
|
-
res.end(JSON.stringify(payload));
|
|
938
|
-
};
|
|
939
|
-
ensureLocalAsr()
|
|
940
|
-
.then(() => send({ ok: true, started: true, phase: 'ready', engine: 'local-sensevoice' }))
|
|
941
|
-
.catch((error) => send({ ok: false, code: 'asr-prepare-failed', hint: String((error && error.message) || error) }));
|
|
942
|
-
}
|
|
943
|
-
|
|
944
|
-
/**
|
|
945
|
-
* GET /pet-chat/selftest —— 语音链路自检。
|
|
946
|
-
* 逐步骤返回,失败即停并把原因带出来:
|
|
947
|
-
* ffmpeg :能不能解析到可执行文件
|
|
948
|
-
* devices :能不能列出音频设备
|
|
949
|
-
* capture :真开麦录 2 秒,返回 wav 字节数
|
|
950
|
-
* asr :用运行时里的 sample.wav 跑一次识别
|
|
951
|
-
*/
|
|
952
|
-
async function handleSelfTest(res) {
|
|
953
|
-
const send = (payload, status = 200) => {
|
|
954
|
-
res.statusCode = status;
|
|
955
|
-
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
956
|
-
res.end(JSON.stringify(payload));
|
|
957
|
-
};
|
|
958
|
-
const steps = {};
|
|
959
|
-
try {
|
|
960
|
-
const ff = await defaultResolveFfmpeg();
|
|
961
|
-
steps.ffmpeg = { ok: true, path: ff };
|
|
962
|
-
let devices = [];
|
|
963
|
-
try { devices = await voiceRecorder.listDevices(); } catch (error) {
|
|
964
|
-
steps.devices = { ok: false, error: String((error && error.message) || error) };
|
|
965
|
-
}
|
|
966
|
-
if (!steps.devices) {
|
|
967
|
-
steps.devices = { ok: devices.length > 0, devices };
|
|
968
|
-
if (devices.length > 0) {
|
|
969
|
-
const dir = mkdtempSync(join(tmpdir(), 'folia-selftest-'));
|
|
970
|
-
const wavPath = join(dir, 'capture.wav');
|
|
971
|
-
const device = devices[0];
|
|
972
|
-
const started = Date.now();
|
|
973
|
-
const captured = await defaultRunFfmpeg(ff, ['-hide_banner', '-y', '-f', 'dshow', '-i', `audio=${device}`, '-ar', '16000', '-ac', '1', '-t', '2', wavPath], 15000);
|
|
974
|
-
let size = 0;
|
|
975
|
-
try { size = statSync(wavPath).size; } catch { size = 0; }
|
|
976
|
-
steps.capture = { ok: captured.code === 0 && size > 1000, device, code: captured.code, bytes: size, ms: Date.now() - started };
|
|
977
|
-
if (steps.capture.ok) {
|
|
978
|
-
const worker = await ensureLocalAsr().catch(() => null);
|
|
979
|
-
if (!worker) {
|
|
980
|
-
steps.asr = { ok: false, error: '本地运行时未就绪' };
|
|
981
|
-
} else {
|
|
982
|
-
const spoken = await worker.request(wavPath, ASR_TIMEOUT_MS).catch((error) => ({ ok: false, error: String((error && error.message) || error) }));
|
|
983
|
-
steps.asr = { ok: !!(spoken && spoken.ok), text: String((spoken && spoken.text) || ''), ms: spoken && spoken.ms, error: spoken && spoken.error };
|
|
984
|
-
}
|
|
985
|
-
}
|
|
986
|
-
try { rmSync(dir, { recursive: true, force: true }); } catch { /* ignore */ }
|
|
987
|
-
}
|
|
988
|
-
}
|
|
989
|
-
send({ ok: Object.values(steps).every((s) => s && s.ok), steps });
|
|
990
|
-
} catch (error) {
|
|
991
|
-
send({ ok: false, steps, error: String((error && error.message) || error) }, 500);
|
|
992
|
-
}
|
|
993
|
-
}
|
|
994
|
-
async function handleConfigGet(res) {
|
|
995
|
-
const config = readPetChat();
|
|
996
|
-
const key = String(config.apiKey || '');
|
|
997
|
-
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
998
|
-
res.end(JSON.stringify({
|
|
999
|
-
ok: true,
|
|
1000
|
-
data: {
|
|
1001
|
-
enabled: config.enabled === true,
|
|
1002
|
-
provider: config.provider,
|
|
1003
|
-
baseUrl: config.baseUrl,
|
|
1004
|
-
model: config.model,
|
|
1005
|
-
apiKeyMasked: key ? `${key.slice(0, 3)}${'•'.repeat(Math.max(4, Math.min(16, key.length - 7)))}${key.slice(-4)}` : '',
|
|
1006
|
-
hasApiKey: Boolean(key),
|
|
1007
|
-
petName: config.petName,
|
|
1008
|
-
ownerName: config.ownerName,
|
|
1009
|
-
voice: config.voice,
|
|
1010
|
-
wake: config.wake,
|
|
1011
|
-
},
|
|
1012
|
-
}));
|
|
1013
|
-
}
|
|
1014
|
-
|
|
1015
|
-
async function handleConfigPost(req, res) {
|
|
1016
|
-
const send = (payload, status = 200) => {
|
|
1017
|
-
res.statusCode = status;
|
|
1018
|
-
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
1019
|
-
res.end(JSON.stringify(payload));
|
|
1020
|
-
};
|
|
1021
|
-
let body = {};
|
|
1022
|
-
try { body = await readJsonBody(req); } catch { send({ ok: false, error: 'bad-json' }, 400); return; }
|
|
1023
|
-
|
|
1024
|
-
// 合并语义:没传 provider 就保持当前值(P2:只改名字却把模型配置冲成 ollama)
|
|
1025
|
-
const current = readPetChat();
|
|
1026
|
-
const hasProvider = body.provider === 'openai' || body.provider === 'ollama';
|
|
1027
|
-
const provider = hasProvider ? body.provider : current.provider;
|
|
1028
|
-
const defaults = PROVIDER_DEFAULTS[provider];
|
|
1029
|
-
const patch = hasProvider ? { provider } : {};
|
|
1030
|
-
|
|
1031
|
-
if (typeof body.enabled === 'boolean') patch.enabled = body.enabled;
|
|
1032
|
-
if (hasProvider && provider === 'ollama') {
|
|
1033
|
-
// 只有**显式切到** ollama 才改地址、清 key(未传 provider 时不能动)
|
|
1034
|
-
patch.baseUrl = defaults.baseUrl;
|
|
1035
|
-
patch.apiKey = '';
|
|
1036
|
-
} else {
|
|
1037
|
-
if (typeof body.baseUrl === 'string' && body.baseUrl.trim()) patch.baseUrl = body.baseUrl.trim().replace(/\/+$/, '');
|
|
1038
|
-
if (typeof body.apiKey === 'string') patch.apiKey = body.apiKey.trim();
|
|
1039
|
-
}
|
|
1040
|
-
if (typeof body.model === 'string' && body.model.trim()) patch.model = body.model.trim();
|
|
1041
|
-
// v0.1:只接受新结构的名字 / 音色 / 唤醒 / 记忆;旧字段(persona/maxTurns/voiceOut/voiceEngine)一律忽略
|
|
1042
|
-
if (typeof body.petName === 'string') patch.petName = body.petName.trim().slice(0, 24);
|
|
1043
|
-
if (typeof body.ownerName === 'string') patch.ownerName = body.ownerName.trim().slice(0, 24);
|
|
1044
|
-
if (body.voice && typeof body.voice === 'object') {
|
|
1045
|
-
patch.voice = {
|
|
1046
|
-
name: String(body.voice.name || 'zh-CN-XiaoxiaoNeural').slice(0, 120),
|
|
1047
|
-
muted: body.voice.muted === true,
|
|
1048
|
-
};
|
|
1049
|
-
}
|
|
1050
|
-
if (body.wake && typeof body.wake === 'object') {
|
|
1051
|
-
patch.wake = {
|
|
1052
|
-
click: body.wake.click !== false,
|
|
1053
|
-
name: body.wake.name === true,
|
|
1054
|
-
keyword: String(body.wake.keyword || '').trim().slice(0, 40),
|
|
1055
|
-
};
|
|
1056
|
-
}
|
|
1057
|
-
|
|
1058
|
-
writeOverlay(patch);
|
|
1059
|
-
const config = readPetChat();
|
|
1060
|
-
send({
|
|
1061
|
-
ok: true,
|
|
1062
|
-
data: { saved: true, enabled: config.enabled, provider: config.provider, baseUrl: config.baseUrl, model: config.model },
|
|
1063
|
-
});
|
|
1064
|
-
}
|
|
1065
|
-
|
|
1066
|
-
/** 真连一次 provider:失败要说清是 401 / 402 / 超时 / 地址错。 */
|
|
1067
|
-
async function handleConfigTest(req, res) {
|
|
1068
|
-
const send = (payload, status = 200) => {
|
|
1069
|
-
res.statusCode = status;
|
|
1070
|
-
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
1071
|
-
res.end(JSON.stringify(payload));
|
|
1072
|
-
};
|
|
1073
|
-
let body = {};
|
|
1074
|
-
try { body = await readJsonBody(req); } catch { body = {}; }
|
|
1075
|
-
const config = readPetChat();
|
|
1076
|
-
const baseUrl = String(body.baseUrl || config.baseUrl || '').replace(/\/+$/, '');
|
|
1077
|
-
const apiKey = typeof body.apiKey === 'string' && body.apiKey.trim() ? body.apiKey.trim() : config.apiKey;
|
|
1078
|
-
const provider = body.provider === 'openai' ? 'openai' : (body.provider === 'ollama' ? 'ollama' : config.provider);
|
|
1079
|
-
if (!baseUrl) { send({ ok: false, code: 'no-base-url', message: '接口地址为空' }); return; }
|
|
1080
|
-
|
|
1081
|
-
const controller = new AbortController();
|
|
1082
|
-
const timer = setTimeout(() => controller.abort(), 8000);
|
|
1083
|
-
try {
|
|
1084
|
-
const response = await fetch(`${baseUrl}/models`, {
|
|
1085
|
-
headers: apiKey ? { authorization: `Bearer ${apiKey}` } : {},
|
|
1086
|
-
signal: controller.signal,
|
|
1087
|
-
});
|
|
1088
|
-
if (response.status === 401 || response.status === 403) {
|
|
1089
|
-
send({ ok: false, code: 'unauthorized', status: response.status, message: 'API Key 无效或没有权限(401)' });
|
|
1090
|
-
return;
|
|
1091
|
-
}
|
|
1092
|
-
if (response.status === 402) { send({ ok: false, code: 'no-balance', status: 402, message: '账号余额不足(402)' }); return; }
|
|
1093
|
-
if (!response.ok) {
|
|
1094
|
-
send({ ok: false, code: 'http', status: response.status, message: `服务返回 ${response.status}` });
|
|
1095
|
-
return;
|
|
1096
|
-
}
|
|
1097
|
-
send({ ok: true, provider, baseUrl, models: 'reachable' });
|
|
1098
|
-
} catch (error) {
|
|
1099
|
-
const aborted = controller.signal.aborted;
|
|
1100
|
-
const message = String((error && error.message) || error);
|
|
1101
|
-
send({
|
|
1102
|
-
ok: false,
|
|
1103
|
-
code: aborted ? 'timeout' : (/ENOTFOUND|EAI_AGAIN|getaddrinfo/.test(message) ? 'dns' : 'network'),
|
|
1104
|
-
message: aborted ? '连接超时(8 秒)' : (/ENOTFOUND|EAI_AGAIN|getaddrinfo/.test(message) ? '地址解析失败,检查接口地址' : `网络错误:${message.slice(0, 80)}`),
|
|
1105
|
-
});
|
|
1106
|
-
} finally {
|
|
1107
|
-
clearTimeout(timer);
|
|
1108
|
-
}
|
|
1109
|
-
}
|
|
1110
|
-
|
|
1111
|
-
/**
|
|
1112
|
-
* 主动搭话(v0.1 零配置):客户端周期性问一次"现在能说吗",策略全在服务端。
|
|
1113
|
-
* 返回 `{ ok, reason, line }`;命中就立刻记账(节奏与当日上限都靠它)。
|
|
1114
|
-
*/
|
|
1115
|
-
async function handleProactiveTick(req, res) {
|
|
1116
|
-
let body = {};
|
|
1117
|
-
try { body = await readJsonBody(req); } catch { body = {}; }
|
|
1118
|
-
const decision = canSpeak({
|
|
1119
|
-
idleMinutes: Number(body.idleMinutes) || 0,
|
|
1120
|
-
fullscreen: body.fullscreen === true,
|
|
1121
|
-
randomHit: body.randomHit !== false,
|
|
1122
|
-
});
|
|
1123
|
-
let line = null;
|
|
1124
|
-
if (decision.ok) {
|
|
1125
|
-
const state = readProactiveState();
|
|
1126
|
-
const built = buildProactiveLine({
|
|
1127
|
-
wallpaperTitle: body.wallpaperTitle,
|
|
1128
|
-
memory: readMemory(),
|
|
1129
|
-
usedLines: state.usedLines,
|
|
1130
|
-
});
|
|
1131
|
-
markSaid(Date.now(), built.line);
|
|
1132
|
-
line = built.line;
|
|
1133
|
-
}
|
|
1134
|
-
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
1135
|
-
res.end(JSON.stringify({ ok: decision.ok, reason: decision.reason, line, usage: todayUsage() }));
|
|
1136
|
-
}
|
|
1137
|
-
|
|
1138
|
-
/** 手动静默(设置页的「暂时不说话」用;语音指令走 handleChat 里的解析)。 */
|
|
1139
|
-
async function handleSilence(req, res) {
|
|
1140
|
-
let body = {};
|
|
1141
|
-
try { body = await readJsonBody(req); } catch { body = {}; }
|
|
1142
|
-
const silent = body.silent !== false;
|
|
1143
|
-
if (silent) enterSilence(); else clearSilence();
|
|
1144
|
-
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
1145
|
-
res.end(JSON.stringify({ ok: true, silent }));
|
|
1146
|
-
}
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
function handleReset(res) {
|
|
1151
|
-
clearMemory();
|
|
1152
|
-
memory = [];
|
|
1153
|
-
lastError = null;
|
|
1154
|
-
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
1155
|
-
res.end(JSON.stringify({ ok: true }));
|
|
1156
|
-
}
|
|
1157
|
-
|
|
1158
|
-
disposers.push(webServer.register({
|
|
1159
|
-
kind: 'prefix',
|
|
1160
|
-
path: `${BASE}/pet-chat`,
|
|
1161
|
-
handler: async (req, res) => {
|
|
1162
|
-
const url = new URL(req.url || '/', 'http://x');
|
|
1163
|
-
const tail = url.pathname.slice(`${BASE}/pet-chat`.length).replace(/\/+$/, '');
|
|
1164
|
-
const method = (req.method || 'GET').toUpperCase();
|
|
1165
|
-
if (tail === '/state' && (method === 'GET' || method === 'HEAD')) { handleState(res); return; }
|
|
1166
|
-
if (tail === '/config' && (method === 'GET' || method === 'HEAD')) { await handleConfigGet(res); return; }
|
|
1167
|
-
if (tail === '/config' && method === 'POST') { await handleConfigPost(req, res); return; }
|
|
1168
|
-
if (tail === '/test' && method === 'POST') { await handleConfigTest(req, res); return; }
|
|
1169
|
-
if (tail === '/models' && (method === 'GET' || method === 'HEAD')) { handleModels(res); return; }
|
|
1170
|
-
if (tail === '/chat' && method === 'POST') { handleChat(req, res); return; }
|
|
1171
|
-
if (tail === '/reset' && method === 'POST') { handleReset(res); return; }
|
|
1172
|
-
if (tail === '/transcribe' && method === 'POST') { handleTranscribe(req, res); return; }
|
|
1173
|
-
if (tail === '/record' && method === 'POST') { await handleRecord(req, res); return; }
|
|
1174
|
-
// 语音模型(SenseVoice)自举:用户不需要去 DSH 设置里找开关,
|
|
1175
|
-
// 插件自己触发 preparation 并轮询进度(DSH 的 speechToText.prepare 是公开方法)。
|
|
1176
|
-
// 自检:一次性跑「ffmpeg → 设备 → 录音 → 转写」四步,把每步结果原样返回。
|
|
1177
|
-
// 目的:发版前/真机排查时**一个请求就能看到哪一步坏了**,不用来回猜。
|
|
1178
|
-
if (tail === '/selftest' && (method === 'GET' || method === 'HEAD')) { void handleSelfTest(res); return; } if (tail === '/asr' && (method === 'GET' || method === 'HEAD')) { handleAsrStatus(res); return; }
|
|
1179
|
-
if (tail === '/asr' && method === 'POST') { handleAsrPrepare(res); return; }
|
|
1180
|
-
// v0.1「零配置」主动搭话:没有开关,只有内部策略 + 语音指令静默
|
|
1181
|
-
if (tail === '/proactive' && (method === 'GET' || method === 'HEAD')) {
|
|
1182
|
-
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
1183
|
-
res.end(JSON.stringify({ ok: true, usage: todayUsage(), silent: isSilent(), rules: PROACTIVE_RULES }));
|
|
1184
|
-
return;
|
|
1185
|
-
}
|
|
1186
|
-
if (tail === '/proactive/tick' && method === 'POST') { await handleProactiveTick(req, res); return; }
|
|
1187
|
-
if (tail === '/silence' && method === 'POST') { await handleSilence(req, res); return; }
|
|
1188
|
-
if (tail === '/memory' && (method === 'GET' || method === 'HEAD')) {
|
|
1189
|
-
// B4:给气泡的「查看记忆」用 —— 只回偏好摘要,不含任何聊天原文
|
|
1190
|
-
const memory = readMemory();
|
|
1191
|
-
const line = memoryPromptLine(memory);
|
|
1192
|
-
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
1193
|
-
res.end(JSON.stringify({ ok: true, memory, line, enabled: true }));
|
|
1194
|
-
return;
|
|
1195
|
-
}
|
|
1196
|
-
if (tail === '/memory' && method === 'DELETE') {
|
|
1197
|
-
// 面板的「清空记忆」:只清偏好记忆,不动对话历史、不动设置
|
|
1198
|
-
clearMemory();
|
|
1199
|
-
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
1200
|
-
res.end(JSON.stringify({ ok: true, cleared: true }));
|
|
1201
|
-
return;
|
|
1202
|
-
}
|
|
1203
|
-
res.statusCode = 404;
|
|
1204
|
-
res.end('not found');
|
|
1205
|
-
},
|
|
1206
|
-
}));
|
|
1207
|
-
}
|
|
1208
|
-
|
|
864
|
+
'unsupported-platform': '这个系统不支持桌面录音,用浏览器打开 DSH 才能语音',
|
|
865
|
+
'ffmpeg-missing': '缺少 ffmpeg,无法录音',
|
|
866
|
+
timeout: '录音超时,再说一次',
|
|
867
|
+
'no-speech': '没听到声音,再说一次或直接打字',
|
|
868
|
+
};
|
|
869
|
+
send({ ok: false, code: result.code, hint: hints[result.code] || '录音失败' }, result.code === 'ffmpeg-missing' ? 503 : 422);
|
|
870
|
+
return;
|
|
871
|
+
}
|
|
872
|
+
// ── 转写:本地 SenseVoice 优先;没装/没下好 ⇒ asr-not-ready,由客户端触发下载 ──
|
|
873
|
+
try {
|
|
874
|
+
const worker = await ensureLocalAsr();
|
|
875
|
+
const spoken = await worker.request(result.audioPath, ASR_TIMEOUT_MS);
|
|
876
|
+
if (!spoken || !spoken.ok) {
|
|
877
|
+
send({ ok: false, code: 'asr-failed', hint: '识别失败,再试一次或直接打字' }, 502);
|
|
878
|
+
return;
|
|
879
|
+
}
|
|
880
|
+
const text = String(spoken.text || '').trim();
|
|
881
|
+
if (!text) { send({ ok: false, code: 'no-speech', hint: '没听清,再说一次' }, 422); return; }
|
|
882
|
+
send({ ok: true, text, ms: spoken.ms, audioSeconds: result.audioSeconds });
|
|
883
|
+
} catch (error) {
|
|
884
|
+
const message = String((error && error.message) || error);
|
|
885
|
+
const notReady = /manifest|下载|ENOENT|缺少/.test(message) || asrState.phase !== 'ready';
|
|
886
|
+
if (notReady) {
|
|
887
|
+
send({ ok: false, code: 'asr-not-ready', hint: ASR_NOT_READY_HINT }, 422);
|
|
888
|
+
} else {
|
|
889
|
+
send({ ok: false, code: 'asr-failed', hint: '转写失败,重试或直接打字' }, 502);
|
|
890
|
+
}
|
|
891
|
+
} finally {
|
|
892
|
+
try {
|
|
893
|
+
const { rmSync } = await import('node:fs');
|
|
894
|
+
if (result.dir) rmSync(result.dir, { recursive: true, force: true });
|
|
895
|
+
} catch { /* ignore */ }
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
/**
|
|
900
|
+
* GET /pet-chat/asr —— 本地 STT 运行时的状态 / 下载进度。
|
|
901
|
+
* phase: idle | downloading | loading | ready | failed
|
|
902
|
+
* downloading 时带 doneBytes / totalBytes(客户端用它显示"下载中 x%")。
|
|
903
|
+
*/
|
|
904
|
+
function handleAsrStatus(res) {
|
|
905
|
+
const send = (payload, status = 200) => {
|
|
906
|
+
res.statusCode = status;
|
|
907
|
+
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
908
|
+
res.end(JSON.stringify(payload));
|
|
909
|
+
};
|
|
910
|
+
if (!asrWorker && asrState.phase === 'idle' && asrInstalledOnDisk()) {
|
|
911
|
+
asrState = { ...asrState, phase: 'ready' };
|
|
912
|
+
}
|
|
913
|
+
const total = Number(asrState.totalBytes) || 0;
|
|
914
|
+
const done = Number(asrState.doneBytes) || 0;
|
|
915
|
+
send({
|
|
916
|
+
ok: true,
|
|
917
|
+
available: true,
|
|
918
|
+
engine: 'local-sensevoice',
|
|
919
|
+
providerId: ASR_PROVIDER_ID,
|
|
920
|
+
phase: asrState.phase,
|
|
921
|
+
completedBytes: done,
|
|
922
|
+
totalBytes: total,
|
|
923
|
+
percent: total > 0 ? Math.min(100, Math.round((done / total) * 100)) : null,
|
|
924
|
+
ready: asrState.phase === 'ready',
|
|
925
|
+
message: asrState.error || null,
|
|
926
|
+
});
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
/**
|
|
930
|
+
* POST /pet-chat/asr —— 触发本地运行时下载(幂等;已在下载会 join 同一个任务)。
|
|
931
|
+
* 用户装完插件点桌宠说话就会走这里,不需要去 DSH 设置里找任何开关。
|
|
932
|
+
*/
|
|
933
|
+
function handleAsrPrepare(res) {
|
|
934
|
+
const send = (payload, status = 200) => {
|
|
935
|
+
res.statusCode = status;
|
|
936
|
+
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
937
|
+
res.end(JSON.stringify(payload));
|
|
938
|
+
};
|
|
939
|
+
ensureLocalAsr()
|
|
940
|
+
.then(() => send({ ok: true, started: true, phase: 'ready', engine: 'local-sensevoice' }))
|
|
941
|
+
.catch((error) => send({ ok: false, code: 'asr-prepare-failed', hint: String((error && error.message) || error) }));
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
/**
|
|
945
|
+
* GET /pet-chat/selftest —— 语音链路自检。
|
|
946
|
+
* 逐步骤返回,失败即停并把原因带出来:
|
|
947
|
+
* ffmpeg :能不能解析到可执行文件
|
|
948
|
+
* devices :能不能列出音频设备
|
|
949
|
+
* capture :真开麦录 2 秒,返回 wav 字节数
|
|
950
|
+
* asr :用运行时里的 sample.wav 跑一次识别
|
|
951
|
+
*/
|
|
952
|
+
async function handleSelfTest(res) {
|
|
953
|
+
const send = (payload, status = 200) => {
|
|
954
|
+
res.statusCode = status;
|
|
955
|
+
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
956
|
+
res.end(JSON.stringify(payload));
|
|
957
|
+
};
|
|
958
|
+
const steps = {};
|
|
959
|
+
try {
|
|
960
|
+
const ff = await defaultResolveFfmpeg();
|
|
961
|
+
steps.ffmpeg = { ok: true, path: ff };
|
|
962
|
+
let devices = [];
|
|
963
|
+
try { devices = await voiceRecorder.listDevices(); } catch (error) {
|
|
964
|
+
steps.devices = { ok: false, error: String((error && error.message) || error) };
|
|
965
|
+
}
|
|
966
|
+
if (!steps.devices) {
|
|
967
|
+
steps.devices = { ok: devices.length > 0, devices };
|
|
968
|
+
if (devices.length > 0) {
|
|
969
|
+
const dir = mkdtempSync(join(tmpdir(), 'folia-selftest-'));
|
|
970
|
+
const wavPath = join(dir, 'capture.wav');
|
|
971
|
+
const device = devices[0];
|
|
972
|
+
const started = Date.now();
|
|
973
|
+
const captured = await defaultRunFfmpeg(ff, ['-hide_banner', '-y', '-f', 'dshow', '-i', `audio=${device}`, '-ar', '16000', '-ac', '1', '-t', '2', wavPath], 15000);
|
|
974
|
+
let size = 0;
|
|
975
|
+
try { size = statSync(wavPath).size; } catch { size = 0; }
|
|
976
|
+
steps.capture = { ok: captured.code === 0 && size > 1000, device, code: captured.code, bytes: size, ms: Date.now() - started };
|
|
977
|
+
if (steps.capture.ok) {
|
|
978
|
+
const worker = await ensureLocalAsr().catch(() => null);
|
|
979
|
+
if (!worker) {
|
|
980
|
+
steps.asr = { ok: false, error: '本地运行时未就绪' };
|
|
981
|
+
} else {
|
|
982
|
+
const spoken = await worker.request(wavPath, ASR_TIMEOUT_MS).catch((error) => ({ ok: false, error: String((error && error.message) || error) }));
|
|
983
|
+
steps.asr = { ok: !!(spoken && spoken.ok), text: String((spoken && spoken.text) || ''), ms: spoken && spoken.ms, error: spoken && spoken.error };
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
try { rmSync(dir, { recursive: true, force: true }); } catch { /* ignore */ }
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
send({ ok: Object.values(steps).every((s) => s && s.ok), steps });
|
|
990
|
+
} catch (error) {
|
|
991
|
+
send({ ok: false, steps, error: String((error && error.message) || error) }, 500);
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
async function handleConfigGet(res) {
|
|
995
|
+
const config = readPetChat();
|
|
996
|
+
const key = String(config.apiKey || '');
|
|
997
|
+
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
998
|
+
res.end(JSON.stringify({
|
|
999
|
+
ok: true,
|
|
1000
|
+
data: {
|
|
1001
|
+
enabled: config.enabled === true,
|
|
1002
|
+
provider: config.provider,
|
|
1003
|
+
baseUrl: config.baseUrl,
|
|
1004
|
+
model: config.model,
|
|
1005
|
+
apiKeyMasked: key ? `${key.slice(0, 3)}${'•'.repeat(Math.max(4, Math.min(16, key.length - 7)))}${key.slice(-4)}` : '',
|
|
1006
|
+
hasApiKey: Boolean(key),
|
|
1007
|
+
petName: config.petName,
|
|
1008
|
+
ownerName: config.ownerName,
|
|
1009
|
+
voice: config.voice,
|
|
1010
|
+
wake: config.wake,
|
|
1011
|
+
},
|
|
1012
|
+
}));
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
async function handleConfigPost(req, res) {
|
|
1016
|
+
const send = (payload, status = 200) => {
|
|
1017
|
+
res.statusCode = status;
|
|
1018
|
+
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
1019
|
+
res.end(JSON.stringify(payload));
|
|
1020
|
+
};
|
|
1021
|
+
let body = {};
|
|
1022
|
+
try { body = await readJsonBody(req); } catch { send({ ok: false, error: 'bad-json' }, 400); return; }
|
|
1023
|
+
|
|
1024
|
+
// 合并语义:没传 provider 就保持当前值(P2:只改名字却把模型配置冲成 ollama)
|
|
1025
|
+
const current = readPetChat();
|
|
1026
|
+
const hasProvider = body.provider === 'openai' || body.provider === 'ollama';
|
|
1027
|
+
const provider = hasProvider ? body.provider : current.provider;
|
|
1028
|
+
const defaults = PROVIDER_DEFAULTS[provider];
|
|
1029
|
+
const patch = hasProvider ? { provider } : {};
|
|
1030
|
+
|
|
1031
|
+
if (typeof body.enabled === 'boolean') patch.enabled = body.enabled;
|
|
1032
|
+
if (hasProvider && provider === 'ollama') {
|
|
1033
|
+
// 只有**显式切到** ollama 才改地址、清 key(未传 provider 时不能动)
|
|
1034
|
+
patch.baseUrl = defaults.baseUrl;
|
|
1035
|
+
patch.apiKey = '';
|
|
1036
|
+
} else {
|
|
1037
|
+
if (typeof body.baseUrl === 'string' && body.baseUrl.trim()) patch.baseUrl = body.baseUrl.trim().replace(/\/+$/, '');
|
|
1038
|
+
if (typeof body.apiKey === 'string') patch.apiKey = body.apiKey.trim();
|
|
1039
|
+
}
|
|
1040
|
+
if (typeof body.model === 'string' && body.model.trim()) patch.model = body.model.trim();
|
|
1041
|
+
// v0.1:只接受新结构的名字 / 音色 / 唤醒 / 记忆;旧字段(persona/maxTurns/voiceOut/voiceEngine)一律忽略
|
|
1042
|
+
if (typeof body.petName === 'string') patch.petName = body.petName.trim().slice(0, 24);
|
|
1043
|
+
if (typeof body.ownerName === 'string') patch.ownerName = body.ownerName.trim().slice(0, 24);
|
|
1044
|
+
if (body.voice && typeof body.voice === 'object') {
|
|
1045
|
+
patch.voice = {
|
|
1046
|
+
name: String(body.voice.name || 'zh-CN-XiaoxiaoNeural').slice(0, 120),
|
|
1047
|
+
muted: body.voice.muted === true,
|
|
1048
|
+
};
|
|
1049
|
+
}
|
|
1050
|
+
if (body.wake && typeof body.wake === 'object') {
|
|
1051
|
+
patch.wake = {
|
|
1052
|
+
click: body.wake.click !== false,
|
|
1053
|
+
name: body.wake.name === true,
|
|
1054
|
+
keyword: String(body.wake.keyword || '').trim().slice(0, 40),
|
|
1055
|
+
};
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
writeOverlay(patch);
|
|
1059
|
+
const config = readPetChat();
|
|
1060
|
+
send({
|
|
1061
|
+
ok: true,
|
|
1062
|
+
data: { saved: true, enabled: config.enabled, provider: config.provider, baseUrl: config.baseUrl, model: config.model },
|
|
1063
|
+
});
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
/** 真连一次 provider:失败要说清是 401 / 402 / 超时 / 地址错。 */
|
|
1067
|
+
async function handleConfigTest(req, res) {
|
|
1068
|
+
const send = (payload, status = 200) => {
|
|
1069
|
+
res.statusCode = status;
|
|
1070
|
+
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
1071
|
+
res.end(JSON.stringify(payload));
|
|
1072
|
+
};
|
|
1073
|
+
let body = {};
|
|
1074
|
+
try { body = await readJsonBody(req); } catch { body = {}; }
|
|
1075
|
+
const config = readPetChat();
|
|
1076
|
+
const baseUrl = String(body.baseUrl || config.baseUrl || '').replace(/\/+$/, '');
|
|
1077
|
+
const apiKey = typeof body.apiKey === 'string' && body.apiKey.trim() ? body.apiKey.trim() : config.apiKey;
|
|
1078
|
+
const provider = body.provider === 'openai' ? 'openai' : (body.provider === 'ollama' ? 'ollama' : config.provider);
|
|
1079
|
+
if (!baseUrl) { send({ ok: false, code: 'no-base-url', message: '接口地址为空' }); return; }
|
|
1080
|
+
|
|
1081
|
+
const controller = new AbortController();
|
|
1082
|
+
const timer = setTimeout(() => controller.abort(), 8000);
|
|
1083
|
+
try {
|
|
1084
|
+
const response = await fetch(`${baseUrl}/models`, {
|
|
1085
|
+
headers: apiKey ? { authorization: `Bearer ${apiKey}` } : {},
|
|
1086
|
+
signal: controller.signal,
|
|
1087
|
+
});
|
|
1088
|
+
if (response.status === 401 || response.status === 403) {
|
|
1089
|
+
send({ ok: false, code: 'unauthorized', status: response.status, message: 'API Key 无效或没有权限(401)' });
|
|
1090
|
+
return;
|
|
1091
|
+
}
|
|
1092
|
+
if (response.status === 402) { send({ ok: false, code: 'no-balance', status: 402, message: '账号余额不足(402)' }); return; }
|
|
1093
|
+
if (!response.ok) {
|
|
1094
|
+
send({ ok: false, code: 'http', status: response.status, message: `服务返回 ${response.status}` });
|
|
1095
|
+
return;
|
|
1096
|
+
}
|
|
1097
|
+
send({ ok: true, provider, baseUrl, models: 'reachable' });
|
|
1098
|
+
} catch (error) {
|
|
1099
|
+
const aborted = controller.signal.aborted;
|
|
1100
|
+
const message = String((error && error.message) || error);
|
|
1101
|
+
send({
|
|
1102
|
+
ok: false,
|
|
1103
|
+
code: aborted ? 'timeout' : (/ENOTFOUND|EAI_AGAIN|getaddrinfo/.test(message) ? 'dns' : 'network'),
|
|
1104
|
+
message: aborted ? '连接超时(8 秒)' : (/ENOTFOUND|EAI_AGAIN|getaddrinfo/.test(message) ? '地址解析失败,检查接口地址' : `网络错误:${message.slice(0, 80)}`),
|
|
1105
|
+
});
|
|
1106
|
+
} finally {
|
|
1107
|
+
clearTimeout(timer);
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
/**
|
|
1112
|
+
* 主动搭话(v0.1 零配置):客户端周期性问一次"现在能说吗",策略全在服务端。
|
|
1113
|
+
* 返回 `{ ok, reason, line }`;命中就立刻记账(节奏与当日上限都靠它)。
|
|
1114
|
+
*/
|
|
1115
|
+
async function handleProactiveTick(req, res) {
|
|
1116
|
+
let body = {};
|
|
1117
|
+
try { body = await readJsonBody(req); } catch { body = {}; }
|
|
1118
|
+
const decision = canSpeak({
|
|
1119
|
+
idleMinutes: Number(body.idleMinutes) || 0,
|
|
1120
|
+
fullscreen: body.fullscreen === true,
|
|
1121
|
+
randomHit: body.randomHit !== false,
|
|
1122
|
+
});
|
|
1123
|
+
let line = null;
|
|
1124
|
+
if (decision.ok) {
|
|
1125
|
+
const state = readProactiveState();
|
|
1126
|
+
const built = buildProactiveLine({
|
|
1127
|
+
wallpaperTitle: body.wallpaperTitle,
|
|
1128
|
+
memory: readMemory(),
|
|
1129
|
+
usedLines: state.usedLines,
|
|
1130
|
+
});
|
|
1131
|
+
markSaid(Date.now(), built.line);
|
|
1132
|
+
line = built.line;
|
|
1133
|
+
}
|
|
1134
|
+
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
1135
|
+
res.end(JSON.stringify({ ok: decision.ok, reason: decision.reason, line, usage: todayUsage() }));
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
/** 手动静默(设置页的「暂时不说话」用;语音指令走 handleChat 里的解析)。 */
|
|
1139
|
+
async function handleSilence(req, res) {
|
|
1140
|
+
let body = {};
|
|
1141
|
+
try { body = await readJsonBody(req); } catch { body = {}; }
|
|
1142
|
+
const silent = body.silent !== false;
|
|
1143
|
+
if (silent) enterSilence(); else clearSilence();
|
|
1144
|
+
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
1145
|
+
res.end(JSON.stringify({ ok: true, silent }));
|
|
1146
|
+
}
|
|
1147
|
+
|
|
1148
|
+
|
|
1149
|
+
|
|
1150
|
+
function handleReset(res) {
|
|
1151
|
+
clearMemory();
|
|
1152
|
+
memory = [];
|
|
1153
|
+
lastError = null;
|
|
1154
|
+
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
1155
|
+
res.end(JSON.stringify({ ok: true }));
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
disposers.push(webServer.register({
|
|
1159
|
+
kind: 'prefix',
|
|
1160
|
+
path: `${BASE}/pet-chat`,
|
|
1161
|
+
handler: async (req, res) => {
|
|
1162
|
+
const url = new URL(req.url || '/', 'http://x');
|
|
1163
|
+
const tail = url.pathname.slice(`${BASE}/pet-chat`.length).replace(/\/+$/, '');
|
|
1164
|
+
const method = (req.method || 'GET').toUpperCase();
|
|
1165
|
+
if (tail === '/state' && (method === 'GET' || method === 'HEAD')) { handleState(res); return; }
|
|
1166
|
+
if (tail === '/config' && (method === 'GET' || method === 'HEAD')) { await handleConfigGet(res); return; }
|
|
1167
|
+
if (tail === '/config' && method === 'POST') { await handleConfigPost(req, res); return; }
|
|
1168
|
+
if (tail === '/test' && method === 'POST') { await handleConfigTest(req, res); return; }
|
|
1169
|
+
if (tail === '/models' && (method === 'GET' || method === 'HEAD')) { handleModels(res); return; }
|
|
1170
|
+
if (tail === '/chat' && method === 'POST') { handleChat(req, res); return; }
|
|
1171
|
+
if (tail === '/reset' && method === 'POST') { handleReset(res); return; }
|
|
1172
|
+
if (tail === '/transcribe' && method === 'POST') { handleTranscribe(req, res); return; }
|
|
1173
|
+
if (tail === '/record' && method === 'POST') { await handleRecord(req, res); return; }
|
|
1174
|
+
// 语音模型(SenseVoice)自举:用户不需要去 DSH 设置里找开关,
|
|
1175
|
+
// 插件自己触发 preparation 并轮询进度(DSH 的 speechToText.prepare 是公开方法)。
|
|
1176
|
+
// 自检:一次性跑「ffmpeg → 设备 → 录音 → 转写」四步,把每步结果原样返回。
|
|
1177
|
+
// 目的:发版前/真机排查时**一个请求就能看到哪一步坏了**,不用来回猜。
|
|
1178
|
+
if (tail === '/selftest' && (method === 'GET' || method === 'HEAD')) { void handleSelfTest(res); return; } if (tail === '/asr' && (method === 'GET' || method === 'HEAD')) { handleAsrStatus(res); return; }
|
|
1179
|
+
if (tail === '/asr' && method === 'POST') { handleAsrPrepare(res); return; }
|
|
1180
|
+
// v0.1「零配置」主动搭话:没有开关,只有内部策略 + 语音指令静默
|
|
1181
|
+
if (tail === '/proactive' && (method === 'GET' || method === 'HEAD')) {
|
|
1182
|
+
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
1183
|
+
res.end(JSON.stringify({ ok: true, usage: todayUsage(), silent: isSilent(), rules: PROACTIVE_RULES }));
|
|
1184
|
+
return;
|
|
1185
|
+
}
|
|
1186
|
+
if (tail === '/proactive/tick' && method === 'POST') { await handleProactiveTick(req, res); return; }
|
|
1187
|
+
if (tail === '/silence' && method === 'POST') { await handleSilence(req, res); return; }
|
|
1188
|
+
if (tail === '/memory' && (method === 'GET' || method === 'HEAD')) {
|
|
1189
|
+
// B4:给气泡的「查看记忆」用 —— 只回偏好摘要,不含任何聊天原文
|
|
1190
|
+
const memory = readMemory();
|
|
1191
|
+
const line = memoryPromptLine(memory);
|
|
1192
|
+
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
1193
|
+
res.end(JSON.stringify({ ok: true, memory, line, enabled: true }));
|
|
1194
|
+
return;
|
|
1195
|
+
}
|
|
1196
|
+
if (tail === '/memory' && method === 'DELETE') {
|
|
1197
|
+
// 面板的「清空记忆」:只清偏好记忆,不动对话历史、不动设置
|
|
1198
|
+
clearMemory();
|
|
1199
|
+
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
1200
|
+
res.end(JSON.stringify({ ok: true, cleared: true }));
|
|
1201
|
+
return;
|
|
1202
|
+
}
|
|
1203
|
+
res.statusCode = 404;
|
|
1204
|
+
res.end('not found');
|
|
1205
|
+
},
|
|
1206
|
+
}));
|
|
1207
|
+
}
|
|
1208
|
+
|