dsh-folia 4.26.0-pre.2 → 4.26.0-pre.21
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/asr/asr-local.js +166 -0
- package/lib/asr/asr-worker.cjs +169 -0
- package/lib/client.js +616 -757
- package/lib/index.js +5 -1
- package/lib/pet-chat-proactive.js +147 -74
- package/lib/routes/pet-chat.js +555 -74
- package/lib/routes/pets.js +30 -2
- package/lib/settings-schema.js +2161 -2168
- package/lib/tts/tts-worker.cjs +129 -0
- package/lib/voice/record.js +217 -0
- package/package.json +5 -1
package/lib/routes/pet-chat.js
CHANGED
|
@@ -24,12 +24,23 @@
|
|
|
24
24
|
// 「语音输入」实验特性)—— 那种情况由路由回 `asr-not-ready`,而不是启动失败。
|
|
25
25
|
export const DEPS = ['disposers', 'base', 'log', 'readSettings', 'speechToText'];
|
|
26
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
|
+
|
|
27
31
|
import {
|
|
28
32
|
readMemory, writeMemory, clearMemory, parseExplicitMemory, rememberExplicit,
|
|
29
33
|
mergeSummary, memoryPromptLine, MEMORY_SUMMARY_PROMPT,
|
|
30
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)
|
|
31
41
|
import {
|
|
32
|
-
canSpeak, markSaid,
|
|
42
|
+
canSpeak, markSaid, buildProactiveLine, readProactiveState, todayUsage, isSilent,
|
|
43
|
+
enterSilence, clearSilence, parseSilenceCommand, PROACTIVE_RULES,
|
|
33
44
|
} from '../pet-chat-proactive.js';
|
|
34
45
|
|
|
35
46
|
/** 单次输入上限(工单:≤400 字)。 */
|
|
@@ -41,6 +52,18 @@ const RATE_LIMIT_MS = 1000;
|
|
|
41
52
|
/** 会话记忆最多保留的轮数(一轮 = 一问一答)。 */
|
|
42
53
|
const MAX_MEMORY_TURNS = 12;
|
|
43
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
|
+
|
|
44
67
|
/* ── 语音转写(PET-CHAT-ROUND-NEXT 之后的一轮)────────────────────────────── */
|
|
45
68
|
/** 单段音频上限:15 秒(16kHz 单声道 PCM16 ≈ 480KB)。 */
|
|
46
69
|
const ASR_MAX_SECONDS = 15;
|
|
@@ -55,7 +78,74 @@ const ASR_PROVIDER_ID = 'sensevoice-local';
|
|
|
55
78
|
/** 转写语言(本功能只做中文;要别的语种先改契约)。 */
|
|
56
79
|
const ASR_LANGUAGE = 'zh';
|
|
57
80
|
/** 未就绪时给用户的一句话(两条路径共用,避免文案漂移)。 */
|
|
58
|
-
const ASR_NOT_READY_HINT = '
|
|
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
|
+
}
|
|
59
149
|
|
|
60
150
|
/**
|
|
61
151
|
* 解析 16kHz 单声道 PCM16 WAV 的时长(秒)。
|
|
@@ -109,7 +199,8 @@ export function decodeBase64(text) {
|
|
|
109
199
|
|
|
110
200
|
/** 各 provider 的默认端点 / 默认模型(设置里 baseUrl / model 为空时用)。 */
|
|
111
201
|
const PROVIDER_DEFAULTS = {
|
|
112
|
-
|
|
202
|
+
// Ollama 的 OpenAI 兼容前缀是 /v1(少了它 /chat/completions 会 404)
|
|
203
|
+
ollama: { baseUrl: 'http://127.0.0.1:11434/v1', model: 'qwen2.5:7b' },
|
|
113
204
|
openai: { baseUrl: 'https://api.deepseek.com', model: 'deepseek-chat' },
|
|
114
205
|
};
|
|
115
206
|
|
|
@@ -241,6 +332,13 @@ function* decodeStreamChunk(provider, line) {
|
|
|
241
332
|
export function registerPetChatRoutes(webServer, c) {
|
|
242
333
|
const { disposers, base: BASE, log, readSettings, speechToText } = c;
|
|
243
334
|
|
|
335
|
+
/** 宿主侧录音器:**必须在这里实例化** —— 只 import 不 new,/record 会抛
|
|
336
|
+
* ReferenceError: voiceRecorder is not defined(P6 实锤)。 */
|
|
337
|
+
const voiceRecorder = createVoiceRecorder({
|
|
338
|
+
resolveFfmpeg: defaultResolveFfmpeg,
|
|
339
|
+
runFfmpeg: defaultRunFfmpeg,
|
|
340
|
+
});
|
|
341
|
+
|
|
244
342
|
/** 当前进程内的会话记忆(重启即忘;`/reset` 清空)。 */
|
|
245
343
|
let memory = [];
|
|
246
344
|
/** 轮次计数(摘要触发用)与最近一次摘要时间。 */
|
|
@@ -253,6 +351,39 @@ export function registerPetChatRoutes(webServer, c) {
|
|
|
253
351
|
/** 最近一次失败原因(`/state` 里回给界面)。 */
|
|
254
352
|
let lastError = null;
|
|
255
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
|
+
|
|
256
387
|
/** 读当前 petChat 配置(每次现读:设置面板改完立刻生效,不用重启)。 */
|
|
257
388
|
function readPetChat() {
|
|
258
389
|
let settings = null;
|
|
@@ -260,36 +391,44 @@ export function registerPetChatRoutes(webServer, c) {
|
|
|
260
391
|
// 读设置失败不能让整条链路炸:当作默认(关)
|
|
261
392
|
log('[pet-chat] 读设置失败:' + String((error && error.message) || error));
|
|
262
393
|
}
|
|
263
|
-
const
|
|
394
|
+
const schemaRaw = settings && typeof settings === 'object' && settings.petChat && typeof settings.petChat === 'object'
|
|
264
395
|
? settings.petChat : {};
|
|
265
|
-
|
|
396
|
+
// 旧键映射只写一处:settings-schema 的 readPetChat 同时负责"默认值 + 迁移"
|
|
397
|
+
const normalized = normalizePetChat({ ...schemaRaw, ...(readOverlay() || {}) });
|
|
398
|
+
const provider = normalized.provider === 'openai' ? 'openai' : 'ollama';
|
|
266
399
|
const defaults = PROVIDER_DEFAULTS[provider];
|
|
267
|
-
const baseUrl = typeof
|
|
400
|
+
const baseUrl = typeof normalized.baseUrl === 'string' && normalized.baseUrl.trim() ? normalized.baseUrl.trim() : defaults.baseUrl;
|
|
268
401
|
return {
|
|
269
|
-
enabled:
|
|
402
|
+
enabled: normalized.enabled === true,
|
|
270
403
|
provider,
|
|
271
404
|
baseUrl: baseUrl.replace(/\/+$/, ''),
|
|
272
|
-
apiKey:
|
|
273
|
-
model: typeof
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
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
|
+
})(),
|
|
285
422
|
};
|
|
286
423
|
}
|
|
287
424
|
|
|
288
425
|
/** 组装请求体(两种协议各一份;都只发到配置里的端点)。 */
|
|
289
426
|
function buildRequest(config, text) {
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
427
|
+
// v0.1:人设不再是一长串设置,只有"名字 / 主人称呼"两项;风格走内置文案
|
|
428
|
+
const petName = config.petName || 'Folia';
|
|
429
|
+
const ownerName = config.ownerName ? `,称呼用户为「${config.ownerName}」` : '';
|
|
430
|
+
let system = `你是${petName}${ownerName},元气、短句、偶尔颜文字、不说教;`
|
|
431
|
+
+ '你的特点:喜欢壁纸和游戏,被夸会害羞。'
|
|
293
432
|
+ `用中文口语回答,最多 ${config.maxChars} 字,不用 Markdown。`
|
|
294
433
|
+ '如果方便,把回答写成 JSON:{"reply":"…","emotion":"happy|calm|tired|angry"};不方便就正常说话。';
|
|
295
434
|
// 工单 A5⑤ 的判据是「第 9 轮只带最近 8 条」⇒ 上限按**条**算(一问一答 = 2 条)
|
|
@@ -351,9 +490,11 @@ export function registerPetChatRoutes(webServer, c) {
|
|
|
351
490
|
model: config.model,
|
|
352
491
|
reachable,
|
|
353
492
|
lastError,
|
|
354
|
-
//
|
|
355
|
-
|
|
356
|
-
|
|
493
|
+
// v0.1:语音输入开关随设置收敛去掉(能力由 DSH 决定);语音/名字照旧回给客户端
|
|
494
|
+
petName: config.petName,
|
|
495
|
+
ownerName: config.ownerName,
|
|
496
|
+
voice: config.voice,
|
|
497
|
+
memoryEnabled: config.memoryEnabled,
|
|
357
498
|
asrProvider: ASR_PROVIDER_ID,
|
|
358
499
|
}));
|
|
359
500
|
}
|
|
@@ -412,6 +553,30 @@ export function registerPetChatRoutes(webServer, c) {
|
|
|
412
553
|
|
|
413
554
|
const config = readPetChat();
|
|
414
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
|
+
|
|
415
580
|
if (config.provider === 'openai' && !config.apiKey) {
|
|
416
581
|
fail('no-model', '填 DeepSeek API Key 即可对话(也可改用本机 Ollama,检测到 127.0.0.1:11434 时会提示)');
|
|
417
582
|
return;
|
|
@@ -523,48 +688,6 @@ export function registerPetChatRoutes(webServer, c) {
|
|
|
523
688
|
}
|
|
524
689
|
}
|
|
525
690
|
|
|
526
|
-
/** C3:主动说话的内容(≤40 字;基于时间 + 记忆里的偏好,不做随机废话)。 */
|
|
527
|
-
function proactiveLine(now) {
|
|
528
|
-
const mem = readMemory();
|
|
529
|
-
const hour = new Date(now).getHours();
|
|
530
|
-
const like = Array.isArray(mem.likes) && mem.likes.length ? mem.likes[0] : '';
|
|
531
|
-
const lines = hour >= 23 || hour < 6
|
|
532
|
-
? ['夜深了,早点休息。', '我先趴一会儿,晚安。']
|
|
533
|
-
: (like
|
|
534
|
-
? [`今天还在看${like}相关的壁纸吗?`, `要不要换一张${like}的?`]
|
|
535
|
-
: ['桌面看累了吧,换一张?', '要不要试试轮播?', '我在这儿,陪你待会儿。']);
|
|
536
|
-
return lines[Math.floor(Math.random() * lines.length)].slice(0, 40);
|
|
537
|
-
}
|
|
538
|
-
|
|
539
|
-
/** C2:客户端问"现在能主动说话吗"。五条件全过才 ok,且 ok 时立刻记一条。 */
|
|
540
|
-
async function handleProactiveTick(req, res) {
|
|
541
|
-
let body = {};
|
|
542
|
-
try { body = await readJsonBody(req); } catch { body = {}; }
|
|
543
|
-
const config = readPetChat();
|
|
544
|
-
const decision = canSpeak({
|
|
545
|
-
enabled: config.proactiveEnabled === true,
|
|
546
|
-
dailyLimit: config.proactiveDailyLimit,
|
|
547
|
-
minGapMin: config.proactiveMinGapMin,
|
|
548
|
-
quietHours: config.quietHours || QUIET_HOURS_DEFAULT,
|
|
549
|
-
idleMinutes: Number(body.idleMinutes) || 0,
|
|
550
|
-
fullscreen: body.fullscreen === true,
|
|
551
|
-
focused: body.focused !== false,
|
|
552
|
-
randomHit: body.randomHit !== false,
|
|
553
|
-
});
|
|
554
|
-
let line = null;
|
|
555
|
-
if (decision.ok) {
|
|
556
|
-
markSaid();
|
|
557
|
-
line = proactiveLine(Date.now());
|
|
558
|
-
}
|
|
559
|
-
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
560
|
-
res.end(JSON.stringify({ ok: decision.ok, reason: decision.reason, line, usage: todayUsage(Date.now(), config.proactiveDailyLimit) }));
|
|
561
|
-
}
|
|
562
|
-
|
|
563
|
-
function handleReset2(res) {
|
|
564
|
-
skipToday();
|
|
565
|
-
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
566
|
-
res.end(JSON.stringify({ ok: true }));
|
|
567
|
-
}
|
|
568
691
|
|
|
569
692
|
/**
|
|
570
693
|
* POST /pet-chat/transcribe —— 把一段 WAV 交给 DSH 宿主的转写服务。
|
|
@@ -624,6 +747,24 @@ export function registerPetChatRoutes(webServer, c) {
|
|
|
624
747
|
asrLastAt.set(ip, nowMs);
|
|
625
748
|
|
|
626
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
|
+
}
|
|
627
768
|
const service = speechToText;
|
|
628
769
|
if (!service || typeof service.snapshot !== 'function' || typeof service.transcribe !== 'function') {
|
|
629
770
|
send({ ok: false, code: 'asr-not-ready', hint: ASR_NOT_READY_HINT });
|
|
@@ -683,6 +824,329 @@ export function registerPetChatRoutes(webServer, c) {
|
|
|
683
824
|
}
|
|
684
825
|
}
|
|
685
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
|
+
'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
|
+
|
|
686
1150
|
function handleReset(res) {
|
|
687
1151
|
clearMemory();
|
|
688
1152
|
memory = [];
|
|
@@ -694,31 +1158,48 @@ export function registerPetChatRoutes(webServer, c) {
|
|
|
694
1158
|
disposers.push(webServer.register({
|
|
695
1159
|
kind: 'prefix',
|
|
696
1160
|
path: `${BASE}/pet-chat`,
|
|
697
|
-
handler: (req, res) => {
|
|
1161
|
+
handler: async (req, res) => {
|
|
698
1162
|
const url = new URL(req.url || '/', 'http://x');
|
|
699
1163
|
const tail = url.pathname.slice(`${BASE}/pet-chat`.length).replace(/\/+$/, '');
|
|
700
1164
|
const method = (req.method || 'GET').toUpperCase();
|
|
701
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; }
|
|
702
1169
|
if (tail === '/models' && (method === 'GET' || method === 'HEAD')) { handleModels(res); return; }
|
|
703
1170
|
if (tail === '/chat' && method === 'POST') { handleChat(req, res); return; }
|
|
704
1171
|
if (tail === '/reset' && method === 'POST') { handleReset(res); return; }
|
|
705
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「零配置」主动搭话:没有开关,只有内部策略 + 语音指令静默
|
|
706
1181
|
if (tail === '/proactive' && (method === 'GET' || method === 'HEAD')) {
|
|
707
|
-
const config = readPetChat();
|
|
708
1182
|
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
709
|
-
res.end(JSON.stringify({ ok: true,
|
|
1183
|
+
res.end(JSON.stringify({ ok: true, usage: todayUsage(), silent: isSilent(), rules: PROACTIVE_RULES }));
|
|
710
1184
|
return;
|
|
711
1185
|
}
|
|
1186
|
+
if (tail === '/proactive/tick' && method === 'POST') { await handleProactiveTick(req, res); return; }
|
|
1187
|
+
if (tail === '/silence' && method === 'POST') { await handleSilence(req, res); return; }
|
|
712
1188
|
if (tail === '/memory' && (method === 'GET' || method === 'HEAD')) {
|
|
713
1189
|
// B4:给气泡的「查看记忆」用 —— 只回偏好摘要,不含任何聊天原文
|
|
714
1190
|
const memory = readMemory();
|
|
715
1191
|
const line = memoryPromptLine(memory);
|
|
716
1192
|
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
717
|
-
res.end(JSON.stringify({ ok: true, memory, line, enabled:
|
|
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 }));
|
|
718
1201
|
return;
|
|
719
1202
|
}
|
|
720
|
-
if (tail === '/proactive/tick' && method === 'POST') { handleProactiveTick(req, res); return; }
|
|
721
|
-
if (tail === '/proactive/skip' && method === 'POST') { handleReset2(res); return; }
|
|
722
1203
|
res.statusCode = 404;
|
|
723
1204
|
res.end('not found');
|
|
724
1205
|
},
|