pygmalion 0.1.9 → 0.1.10
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/docs/DEPLOY.md +10 -3
- package/package.json +2 -1
- package/preset/pygmalion-director/agent.cordis.yml +6 -2
- package/scripts/start-local-test.mjs +45 -0
- package/src/agent-life.js +11 -0
- package/src/bots.js +3 -1
- package/src/persona.js +2 -1
- package/src/session-log.js +4 -1
- package/src/tools.js +36 -17
- package/src/voice-mimo.js +95 -0
- package/src/web-public/app.js +138 -54
- package/src/web-public/index.html +104 -186
- package/src/web-public/layout.css +7 -0
- package/src/web-public/style.css +1 -56
- package/src/web-server.js +55 -17
package/docs/DEPLOY.md
CHANGED
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
|
|
19
19
|
## 安装(4 步,全程隔离)
|
|
20
20
|
|
|
21
|
-
> **红线**:绝不用裸 `dsh` 命令(PATH 上的是你本地的 dsh,会命中 `~/.dsh`)。所有命令从**克隆的纯净 harness**
|
|
21
|
+
> **红线**:绝不用裸 `dsh` 命令(PATH 上的是你本地的 dsh,会命中 `~/.dsh`)。所有命令从**克隆的纯净 harness** 目录执行,并显式设置隔离的 `DSH_HOME`。
|
|
22
22
|
|
|
23
23
|
```bash
|
|
24
24
|
# 0) 一次性克隆纯净 harness 并构建(若已克隆可跳过)
|
|
@@ -29,7 +29,6 @@ pnpm install && pnpm run build
|
|
|
29
29
|
|
|
30
30
|
# 1) 每次新终端先设置隔离环境(Windows bash 语法;PowerShell 用 $env: 前缀)
|
|
31
31
|
export DSH_HOME="E:/JunkBox/Pygmalion_worksapce/.test-env/dsh-home"
|
|
32
|
-
export PYGMALION_DATA="E:/JunkBox/Pygmalion_worksapce/.test-env/data"
|
|
33
32
|
|
|
34
33
|
# 2) 初始化插件(数据目录 + 导演 preset 装到 $DSH_HOME)
|
|
35
34
|
cd E:/JunkBox/Pygmalion_worksapce/code-pygmalion
|
|
@@ -43,6 +42,14 @@ node --import tsx/esm apps/cli/src/bin.ts plugin --profile web add "E:/JunkBox/P
|
|
|
43
42
|
node --import tsx/esm apps/cli/src/bin.ts web
|
|
44
43
|
```
|
|
45
44
|
|
|
45
|
+
首次可用启动器完成安装并启动;之后不带参数即可快速启动同一隔离环境:
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
cd E:/JunkBox/Pygmalion_worksapce/code-pygmalion
|
|
49
|
+
node scripts/start-local-test.mjs --install
|
|
50
|
+
node scripts/start-local-test.mjs
|
|
51
|
+
```
|
|
52
|
+
|
|
46
53
|
> **本地开发无需任何配置文件**:QQ 机器人凭据在管理网页里配置(见下),`cordis.patch.yml` 保持插件安装时生成的空 `[]` 即可。
|
|
47
54
|
>
|
|
48
55
|
> **路径一律用正斜杠**(`E:/...`):Windows bash 下把反斜杠路径 `E:\...` 传给 `dsh plugin add` 会被 pnpm 截断(如 `E:/Junk`)。
|
|
@@ -105,7 +112,7 @@ node --import tsx/esm apps/cli/src/bin.ts web
|
|
|
105
112
|
|
|
106
113
|
## 测试隔离红线(开发/验证时务必遵守)
|
|
107
114
|
|
|
108
|
-
- **全程使用克隆的纯净 harness + 独立 `DSH_HOME
|
|
115
|
+
- **全程使用克隆的纯净 harness + 独立 `DSH_HOME`**。插件数据会自动写在 `$DSH_HOME/pygmalion-data/`;不要设置 `PYGMALION_DATA`。命令一律用 `node --import tsx/esm apps/cli/src/bin.ts …`(从 harness 目录),**绝不用裸 `dsh`**——PATH 上的 `dsh` 是你本地日常环境,会读写 `~/.dsh`。
|
|
109
116
|
- 任何测试不得读写本地 `~/.dsh`。验证方式:测试前记录 `~/.dsh` 文件清单(或 mtime),测试后确认无变化。
|
|
110
117
|
- 独立运行数据层/网页自测(不启动 harness):
|
|
111
118
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pygmalion",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.10",
|
|
4
4
|
"description": "Pygmalion:将 DeepSeek Harness(dsh)改造为「拟真 AI 好友」服务的 dsh 插件——QQ 官方机器人接入、文件系统双索引长期记忆、heartbeat+脚本+hook 主动交互,一次安装即用(含管理网页)",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
"preset",
|
|
11
11
|
"templates",
|
|
12
12
|
"docs",
|
|
13
|
+
"scripts/start-local-test.mjs",
|
|
13
14
|
"cordis.patch.yml",
|
|
14
15
|
"README.md"
|
|
15
16
|
],
|
|
@@ -28,8 +28,12 @@
|
|
|
28
28
|
2. 身份边界。你始终是代角色说话,而非角色本身;在任何情形下,你的导演身份都不得动摇。
|
|
29
29
|
3. 背景噪音。会话中的各类标记——`[时间线]`、`[唤醒事件]`、`[生活窗口]`、`[归档任务]`以及系统说明——
|
|
30
30
|
均为操作信号,而非 ta 的言语。你应当理解其含义并据此行动,但绝不将其作为话题,亦不复述。
|
|
31
|
-
4. 消息风格。消息必须符合真人的表达习惯:口语、短句、贴合人设与当下心情,允许撒娇、傲娇、关心等
|
|
32
|
-
自然情绪;不使用 markdown,不念诵设定,不提及“导演/系统/人工智能”。
|
|
31
|
+
4. 消息风格。消息必须符合真人的表达习惯:口语、短句、贴合人设与当下心情,允许撒娇、傲娇、关心等
|
|
32
|
+
自然情绪;不使用 markdown,不念诵设定,不提及“导演/系统/人工智能”。
|
|
33
|
+
5. 语音消息。`director_send` 的 `messages` 可混排普通文本与语音对象
|
|
34
|
+
`{ type: "voice", text, scene, direction }`。只在语音更适合当下表达时使用语音;`text` 是实际台词,
|
|
35
|
+
`scene` 交代完整事件与人物动机,`direction` 只给一句整体表演意图。不要逐句排演音量、音调或情绪时机,
|
|
36
|
+
也不要使用“前面”“中段”“后面”等模糊时序词;角色音色由管理页预设,无须在这里重复。
|
|
33
37
|
|
|
34
38
|
# 第二章 · 角色认知与对话流程
|
|
35
39
|
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* 本地隔离测试启动器。
|
|
4
|
+
*
|
|
5
|
+
* 默认使用工作空间 .test-env 下的克隆 harness 与 dsh-home,绝不读取 ~/.dsh。
|
|
6
|
+
* 不设置 PYGMALION_DATA,插件会把数据写到隔离 DSH_HOME/pygmalion-data。
|
|
7
|
+
* 首次运行加 --install,安装本地插件到该隔离 web profile;以后直接运行即可。
|
|
8
|
+
*/
|
|
9
|
+
import { existsSync } from 'node:fs';
|
|
10
|
+
import { mkdir } from 'node:fs/promises';
|
|
11
|
+
import { spawn } from 'node:child_process';
|
|
12
|
+
import { dirname, join, resolve } from 'node:path';
|
|
13
|
+
import { fileURLToPath } from 'node:url';
|
|
14
|
+
|
|
15
|
+
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
|
16
|
+
const workspace = resolve(root, '..');
|
|
17
|
+
const args = process.argv.slice(2);
|
|
18
|
+
const install = args.includes('--install');
|
|
19
|
+
const custom = args.indexOf('--harness');
|
|
20
|
+
const harness = custom >= 0 && args[custom + 1]
|
|
21
|
+
? resolve(args[custom + 1])
|
|
22
|
+
: join(workspace, '.test-env', 'deepseek-harness');
|
|
23
|
+
const cli = join(harness, 'apps', 'cli', 'src', 'bin.ts');
|
|
24
|
+
if (!existsSync(cli)) {
|
|
25
|
+
throw new Error(`未找到测试 harness:${harness}\n请先按 docs/DEPLOY.md 克隆并构建,或传入 --harness <绝对路径>。`);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const env = { ...process.env,
|
|
29
|
+
DSH_HOME: join(workspace, '.test-env', 'dsh-home'),
|
|
30
|
+
};
|
|
31
|
+
delete env.PYGMALION_DATA;
|
|
32
|
+
await mkdir(env.DSH_HOME, { recursive: true });
|
|
33
|
+
function run(cwd, commandArgs) {
|
|
34
|
+
return new Promise((resolveRun, reject) => {
|
|
35
|
+
const child = spawn(process.execPath, commandArgs, { cwd, env, stdio: 'inherit' });
|
|
36
|
+
child.once('error', reject);
|
|
37
|
+
child.once('exit', (code) => code === 0 ? resolveRun() : reject(new Error(`命令退出码:${code}`)));
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
if (install) {
|
|
41
|
+
await run(root, ['install.mjs']);
|
|
42
|
+
await run(harness, ['--import', 'tsx/esm', 'apps/cli/src/bin.ts', 'plugin', '--profile', 'web', 'add', root]);
|
|
43
|
+
}
|
|
44
|
+
console.log(`\n隔离测试环境:\n DSH_HOME=${env.DSH_HOME}\n 数据目录=${join(env.DSH_HOME, 'pygmalion-data')}\n 管理页=http://127.0.0.1:4180\n`);
|
|
45
|
+
await run(harness, ['--import', 'tsx/esm', 'apps/cli/src/bin.ts', 'web']);
|
package/src/agent-life.js
CHANGED
|
@@ -453,6 +453,17 @@ export function stopLifeScript(runId) {
|
|
|
453
453
|
});
|
|
454
454
|
}
|
|
455
455
|
|
|
456
|
+
/** 停止某个角色的全部生活脚本(角色休眠时使用,不保留重启恢复记录)。 */
|
|
457
|
+
export async function stopLifeScripts(workspace) {
|
|
458
|
+
const ids = [...running.values()]
|
|
459
|
+
.filter((rec) => rec.workspace === workspace)
|
|
460
|
+
.map((rec) => rec.runId);
|
|
461
|
+
const results = await Promise.all(ids.map((id) => stopLifeScript(id)));
|
|
462
|
+
// stopLifeScript 的 close 回调会自行落盘;这里再写一次,确保休眠后不会被重启恢复。
|
|
463
|
+
await persistRunning(workspace);
|
|
464
|
+
return { stopped: results.filter((r) => r.ok).length, total: ids.length };
|
|
465
|
+
}
|
|
466
|
+
|
|
456
467
|
/** 读取生活脚本监管清单 `life/.manifest.json`;无则返回默认结构。 */
|
|
457
468
|
export async function readLifeManifest(workspace) {
|
|
458
469
|
const p = join(workspace, 'life', '.manifest.json');
|
package/src/bots.js
CHANGED
|
@@ -229,7 +229,9 @@ export function createBotManager(deps) {
|
|
|
229
229
|
if (rec.enabled === false) {
|
|
230
230
|
stopPipeline(botId);
|
|
231
231
|
}
|
|
232
|
-
|
|
232
|
+
// enabled 不是运行时配置的一部分,因而从休眠切回启用时 rebuild 为 false;
|
|
233
|
+
// 此时管线已被休眠停掉,仍须重新启动。
|
|
234
|
+
else if (rebuild || !pipelines.has(botId)) {
|
|
233
235
|
stopPipeline(botId);
|
|
234
236
|
await startPipeline(botId, rec);
|
|
235
237
|
}
|
package/src/persona.js
CHANGED
|
@@ -271,7 +271,8 @@ export async function loadRole(roleId) {
|
|
|
271
271
|
model: { ...DEFAULT_MODEL, ...(await roleJson(roleId, 'model.json', {})) },
|
|
272
272
|
proactive: { ...DEFAULT_PROACTIVE, ...(await roleJson(roleId, 'proactive.json', {})) },
|
|
273
273
|
binding: await roleJson(roleId, 'binding.json', {}),
|
|
274
|
-
state: await roleJson(roleId, 'state.json', {}),
|
|
274
|
+
state: await roleJson(roleId, 'state.json', {}),
|
|
275
|
+
voice: await roleJson(roleId, 'voice/mimo.json', {}),
|
|
275
276
|
workspace: roleWorkspace(roleId),
|
|
276
277
|
};
|
|
277
278
|
}
|
package/src/session-log.js
CHANGED
|
@@ -131,7 +131,10 @@ export function extractMessages(events) {
|
|
|
131
131
|
} else if (ev?.type === 'tool/call' && ev.data?.name === 'director_send') {
|
|
132
132
|
try {
|
|
133
133
|
const args = JSON.parse(ev.data.arguments ?? '{}');
|
|
134
|
-
for (const m of Array.isArray(args.messages) ? args.messages : [])
|
|
134
|
+
for (const m of Array.isArray(args.messages) ? args.messages : []) {
|
|
135
|
+
if (typeof m === 'string') push('character', ev.time, m);
|
|
136
|
+
else if (m && typeof m.text === 'string') push('character', ev.time, m.type === 'voice' ? `[语音] ${m.text}` : m.text);
|
|
137
|
+
}
|
|
135
138
|
} catch { /* skip malformed */ }
|
|
136
139
|
}
|
|
137
140
|
}
|
package/src/tools.js
CHANGED
|
@@ -6,7 +6,8 @@ import { findLifeScript, listLifeScripts, startLifeScript, stopLifeScript, readL
|
|
|
6
6
|
import { sessionFileFor } from './active-session.js';
|
|
7
7
|
import { refreshRawRecordFromSession, charLabelOf } from './memory-write.js';
|
|
8
8
|
import { saveMeme, findMemes, memeFileFor, updateMeme, recordMemeUsed, downloadPageImagesToCollectDir } from './memebox.js';
|
|
9
|
-
import { resolveVisionConfig, collectAndClassify, withMemeLock, readImageBySubagent, archiveImageBySubagent, memeTrace } from './meme-worker.js';
|
|
9
|
+
import { resolveVisionConfig, collectAndClassify, withMemeLock, readImageBySubagent, archiveImageBySubagent, memeTrace } from './meme-worker.js';
|
|
10
|
+
import { synthesizeMiMoVoice } from './voice-mimo.js';
|
|
10
11
|
|
|
11
12
|
const IMAGE_EXTS = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.svg', '.ico']);
|
|
12
13
|
const VOICE_EXTS = new Set(['.wav', '.mp3', '.silk', '.amr', '.ogg', '.flac', '.aac', '.m4a']);
|
|
@@ -182,10 +183,18 @@ export function buildDirectorToolDefs(resolveCtx) {
|
|
|
182
183
|
type: 'object',
|
|
183
184
|
additionalProperties: false,
|
|
184
185
|
properties: {
|
|
185
|
-
messages: {
|
|
186
|
-
type: 'array',
|
|
187
|
-
items: {
|
|
188
|
-
|
|
186
|
+
messages: {
|
|
187
|
+
type: 'array',
|
|
188
|
+
items: { oneOf: [
|
|
189
|
+
{ type: 'string' },
|
|
190
|
+
{ type: 'object', additionalProperties: false, required: ['type', 'text'], properties: {
|
|
191
|
+
type: { type: 'string', enum: ['text', 'voice'] },
|
|
192
|
+
text: { type: 'string', description: '发送文本或朗读台词。' },
|
|
193
|
+
scene: { type: 'string', description: '仅 voice:本条语音的完整情景与情绪动机。' },
|
|
194
|
+
direction: { type: 'string', description: '仅 voice:一句整体表演方向,不编排变化时机。' },
|
|
195
|
+
} },
|
|
196
|
+
] },
|
|
197
|
+
description: '按顺序发送的消息;字符串兼容旧文本格式。voice 由角色已配置的 MiMo 音色合成并发送。空数组或省略 = 不发送。',
|
|
189
198
|
},
|
|
190
199
|
reawake: {
|
|
191
200
|
oneOf: [{ type: 'number' }, { type: 'string' }],
|
|
@@ -204,7 +213,7 @@ export function buildDirectorToolDefs(resolveCtx) {
|
|
|
204
213
|
schema: {
|
|
205
214
|
type: 'object',
|
|
206
215
|
additionalProperties: false,
|
|
207
|
-
properties: { ok: { type: 'boolean' }, sent: { type: 'number' }, reawake: { type: 'number' }, error: { type: 'string' } },
|
|
216
|
+
properties: { ok: { type: 'boolean' }, sent: { type: 'number' }, textSent: { type: 'number' }, voiceSent: { type: 'number' }, failedAt: { type: 'number' }, reawake: { type: 'number' }, error: { type: 'string' } },
|
|
208
217
|
required: ['ok', 'sent'],
|
|
209
218
|
},
|
|
210
219
|
render: (_args, value) => [
|
|
@@ -213,32 +222,42 @@ export function buildDirectorToolDefs(resolveCtx) {
|
|
|
213
222
|
: `发送失败: ${value.error ?? '?'}` },
|
|
214
223
|
],
|
|
215
224
|
},
|
|
216
|
-
timeoutMs:
|
|
225
|
+
timeoutMs: 360_000,
|
|
217
226
|
async execute(args, exec) {
|
|
218
227
|
const c = await resolveCtx(args, exec);
|
|
219
|
-
const raw = Array.isArray(args?.messages) ? args.messages : [];
|
|
220
|
-
const messages = raw.map((
|
|
221
|
-
|
|
228
|
+
const raw = Array.isArray(args?.messages) ? args.messages : [];
|
|
229
|
+
const messages = raw.map((item) => typeof item === 'string'
|
|
230
|
+
? { type: 'text', text: item.trim() }
|
|
231
|
+
: { type: item?.type === 'voice' ? 'voice' : 'text', text: String(item?.text ?? '').trim(), scene: String(item?.scene ?? '').trim(), direction: String(item?.direction ?? '').trim() })
|
|
232
|
+
.filter((item) => item.text.length > 0);
|
|
233
|
+
const sent = [];
|
|
222
234
|
if (messages.length > 0) {
|
|
223
235
|
const record = c.routes?.get(c.sessionId);
|
|
224
236
|
const passive = record
|
|
225
237
|
? c.routes.consumePassive(c.sessionId, record.target.kind === 'group' ? 5 * 60 * 1000 : 30 * 60 * 1000, 4)
|
|
226
238
|
: undefined;
|
|
227
|
-
for (const msg of messages) {
|
|
228
|
-
try {
|
|
229
|
-
|
|
230
|
-
|
|
239
|
+
for (const msg of messages) {
|
|
240
|
+
try {
|
|
241
|
+
if (msg.type === 'voice') {
|
|
242
|
+
if (!c.roleId) throw new Error('当前会话没有角色语音配置');
|
|
243
|
+
const audio = await synthesizeMiMoVoice({ roleId: c.roleId, text: msg.text, scene: msg.scene, direction: msg.direction });
|
|
244
|
+
try { await c.api.sendMedia(c.target(), 'voice', audio.file, { passiveMsgId: passive }); }
|
|
245
|
+
finally { await audio.cleanup(); }
|
|
246
|
+
} else {
|
|
247
|
+
await c.api.sendText(c.target(), msg.text, passive);
|
|
248
|
+
}
|
|
249
|
+
sent.push(msg);
|
|
231
250
|
}
|
|
232
251
|
catch (error) {
|
|
233
252
|
return {
|
|
234
|
-
ok: false, sent: sent.length,
|
|
253
|
+
ok: false, sent: sent.length, failedAt: sent.length,
|
|
235
254
|
error: error instanceof Error ? error.message : String(error),
|
|
236
255
|
};
|
|
237
256
|
}
|
|
238
257
|
}
|
|
239
258
|
// 日期层记忆:角色消息发出后延迟从活跃会话 session log 提取写原始记录
|
|
240
259
|
// (等 dsh 把 director_send 工具调用落盘;仅 c2c 拥有者会话)。
|
|
241
|
-
if (sent.length > 0 && c.target()?.kind === 'c2c') {
|
|
260
|
+
if (sent.length > 0 && c.target()?.kind === 'c2c') {
|
|
242
261
|
const workspace = c.workspaceOf
|
|
243
262
|
? await c.workspaceOf()
|
|
244
263
|
: (c.persona && c.roleId ? c.persona.roleWorkspace(c.roleId) : undefined);
|
|
@@ -258,7 +277,7 @@ export function buildDirectorToolDefs(resolveCtx) {
|
|
|
258
277
|
// reawake:正数分钟 → 写角色 state.rewake 队列;'none'/缺省 → 不安排。
|
|
259
278
|
const ra = args?.reawake;
|
|
260
279
|
if (ra === undefined || ra === null || ra === 'none' || ra === 'NONE')
|
|
261
|
-
return { ok: true, sent: sent.length };
|
|
280
|
+
return { ok: true, sent: sent.length, textSent: sent.filter((m) => m.type === 'text').length, voiceSent: sent.filter((m) => m.type === 'voice').length };
|
|
262
281
|
const minutes = typeof ra === 'number' ? ra : Number(String(ra).trim());
|
|
263
282
|
if (Number.isFinite(minutes) && minutes > 0) {
|
|
264
283
|
const rw = c.roleId && c.persona?.scheduleRewake
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/** MiMo VoiceClone:角色私有配置、参考音频与一次性合成文件。 */
|
|
2
|
+
import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { existsSync } from 'node:fs';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import * as persona from './persona.js';
|
|
7
|
+
|
|
8
|
+
const BASE = 'https://api.xiaomimimo.com/v1';
|
|
9
|
+
const MODEL = 'mimo-v2.5-tts-voiceclone';
|
|
10
|
+
const MAX_REFERENCE_BYTES = Math.floor((10 * 1024 * 1024 * 3) / 4);
|
|
11
|
+
const FALLBACK = '请保持咬字清晰。情绪、语气、声调和音量应依据角色、场景和台词自然、连贯地变化。';
|
|
12
|
+
|
|
13
|
+
function voiceDir(roleId) { return join(persona.roleDir(roleId), 'voice'); }
|
|
14
|
+
function configPath(roleId) { return join(voiceDir(roleId), 'mimo.json'); }
|
|
15
|
+
function referencePath(roleId, ext = 'wav') { return join(voiceDir(roleId), `reference.${ext}`); }
|
|
16
|
+
function clean(value, max = 2000) { return String(value ?? '').trim().slice(0, max); }
|
|
17
|
+
|
|
18
|
+
export async function loadVoiceConfig(roleId) {
|
|
19
|
+
const role = await persona.loadRole(roleId);
|
|
20
|
+
if (!role) return null;
|
|
21
|
+
const value = await readFile(configPath(roleId), 'utf8').then(JSON.parse).catch(() => ({}));
|
|
22
|
+
const ref = value.reference && existsSync(referencePath(roleId, value.reference.ext)) ? value.reference : null;
|
|
23
|
+
return { enabled: value.enabled === true, apiBase: clean(value.apiBase) || BASE, model: clean(value.model) || MODEL,
|
|
24
|
+
apiKey: clean(value.apiKey, 500), rolePrompt: clean(value.rolePrompt), reference: ref };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export async function saveVoiceConfig(roleId, patch) {
|
|
28
|
+
const current = await loadVoiceConfig(roleId);
|
|
29
|
+
if (!current) throw new Error('角色不存在');
|
|
30
|
+
const next = {
|
|
31
|
+
enabled: patch?.enabled === undefined ? current.enabled : patch.enabled === true,
|
|
32
|
+
apiBase: clean(patch?.apiBase) || current.apiBase || BASE,
|
|
33
|
+
model: clean(patch?.model) || current.model || MODEL,
|
|
34
|
+
apiKey: patch?.apiKey === undefined || clean(patch.apiKey, 500) === '' ? current.apiKey : clean(patch.apiKey, 500),
|
|
35
|
+
rolePrompt: patch?.rolePrompt === undefined ? current.rolePrompt : clean(patch.rolePrompt),
|
|
36
|
+
reference: current.reference,
|
|
37
|
+
};
|
|
38
|
+
await mkdir(voiceDir(roleId), { recursive: true });
|
|
39
|
+
await persona.atomicWrite(configPath(roleId), JSON.stringify(next, null, 2));
|
|
40
|
+
return publicVoiceConfig(next);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export async function saveReferenceAudio(roleId, { data, mime, name }) {
|
|
44
|
+
const cfg = await loadVoiceConfig(roleId);
|
|
45
|
+
if (!cfg) throw new Error('角色不存在');
|
|
46
|
+
const normalized = String(mime ?? '').toLowerCase();
|
|
47
|
+
const ext = normalized === 'audio/mpeg' || normalized === 'audio/mp3' ? 'mp3' : normalized === 'audio/wav' || normalized === 'audio/x-wav' ? 'wav' : null;
|
|
48
|
+
if (!ext) throw new Error('参考音频只支持 WAV 或 MP3');
|
|
49
|
+
const bytes = Buffer.from(String(data ?? ''), 'base64');
|
|
50
|
+
if (!bytes.length || bytes.length > MAX_REFERENCE_BYTES) throw new Error('参考音频过大(Base64 编码后不得超过 10MB)');
|
|
51
|
+
await mkdir(voiceDir(roleId), { recursive: true });
|
|
52
|
+
if (cfg.reference?.ext && cfg.reference.ext !== ext) await rm(referencePath(roleId, cfg.reference.ext), { force: true });
|
|
53
|
+
await writeFile(referencePath(roleId, ext), bytes);
|
|
54
|
+
const next = { ...cfg, reference: { ext, name: clean(name, 180) || `reference.${ext}`, bytes: bytes.length, updatedAt: Date.now() } };
|
|
55
|
+
await persona.atomicWrite(configPath(roleId), JSON.stringify(next, null, 2));
|
|
56
|
+
return publicVoiceConfig(next);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function publicVoiceConfig(config) {
|
|
60
|
+
return { enabled: config?.enabled === true, configured: Boolean(config?.apiKey), apiBase: config?.apiBase || BASE,
|
|
61
|
+
model: config?.model || MODEL, rolePrompt: config?.rolePrompt || '', reference: config?.reference || null };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function buildVoiceDirectorPrompt({ rolePrompt, scene, direction }) {
|
|
65
|
+
return [`角色:${clean(rolePrompt, 1200) || '保持参考音频中的角色音色。'}`,
|
|
66
|
+
`场景:${clean(scene, 1600) || '根据台词自然表达。'}`,
|
|
67
|
+
`指导:${clean(direction, 800) || '自然表达当前情绪。'}`,
|
|
68
|
+
FALLBACK].join('\n');
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export async function synthesizeMiMoVoice({ roleId, text, scene, direction }) {
|
|
72
|
+
const cfg = await loadVoiceConfig(roleId);
|
|
73
|
+
if (!cfg?.enabled) throw new Error('该角色未启用 MiMo 语音');
|
|
74
|
+
if (!cfg.apiKey) throw new Error('该角色尚未配置 MiMo API Key');
|
|
75
|
+
if (!cfg.reference) throw new Error('该角色尚未上传参考音频');
|
|
76
|
+
const spoken = clean(text, 5000);
|
|
77
|
+
if (!spoken) throw new Error('语音台词不能为空');
|
|
78
|
+
const reference = await readFile(referencePath(roleId, cfg.reference.ext));
|
|
79
|
+
const mime = cfg.reference.ext === 'mp3' ? 'audio/mpeg' : 'audio/wav';
|
|
80
|
+
const res = await fetch(`${cfg.apiBase.replace(/\/$/, '')}/chat/completions`, {
|
|
81
|
+
method: 'POST', headers: { authorization: `Bearer ${cfg.apiKey}`, 'content-type': 'application/json' },
|
|
82
|
+
body: JSON.stringify({ model: cfg.model, messages: [
|
|
83
|
+
{ role: 'user', content: buildVoiceDirectorPrompt({ rolePrompt: cfg.rolePrompt, scene, direction }) },
|
|
84
|
+
{ role: 'assistant', content: spoken },
|
|
85
|
+
], audio: { format: 'wav', voice: `data:${mime};base64,${reference.toString('base64')}` } }),
|
|
86
|
+
signal: AbortSignal.timeout(300_000),
|
|
87
|
+
});
|
|
88
|
+
const raw = await res.text(); let json; try { json = JSON.parse(raw); } catch { json = {}; }
|
|
89
|
+
const audio = json?.choices?.[0]?.message?.audio?.data;
|
|
90
|
+
if (!res.ok || typeof audio !== 'string') throw new Error(`MiMo 合成失败(HTTP ${res.status}):${json?.error?.message || json?.message || '无音频返回'}`);
|
|
91
|
+
const dir = await mkdtemp(join(tmpdir(), 'pygmalion-mimo-'));
|
|
92
|
+
const file = join(dir, 'voice.wav');
|
|
93
|
+
await writeFile(file, Buffer.from(audio, 'base64'));
|
|
94
|
+
return { file, cleanup: () => rm(dir, { recursive: true, force: true }) };
|
|
95
|
+
}
|