pygmalion 0.1.9 → 0.1.11

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 CHANGED
@@ -18,7 +18,7 @@
18
18
 
19
19
  ## 安装(4 步,全程隔离)
20
20
 
21
- > **红线**:绝不用裸 `dsh` 命令(PATH 上的是你本地的 dsh,会命中 `~/.dsh`)。所有命令从**克隆的纯净 harness** 目录执行,并显式设置 `DSH_HOME` / `PYGMALION_DATA` 到隔离目录。
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` + 独立 `PYGMALION_DATA`**。命令一律用 `node --import tsx/esm apps/cli/src/bin.ts …`(从 harness 目录),**绝不用裸 `dsh`**——PATH 上的 `dsh` 是你本地日常环境,会读写 `~/.dsh`。
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.9",
3
+ "version": "0.1.11",
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,25 @@
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
+ 也不要使用“前面”“中段”“后面”等模糊时序词;角色音色由管理页预设,无须在这里重复。
37
+ 场景必须说明当前发生的事、对谁说、角色为何会这样说;指导只描述整段成立的情绪关系或说话状态,
38
+ 不能替模型规定每一句的声学动作,不得加入台词外的心理独白或旁白。`text` 中允许保留或加入简短的中文圆括号语义标签,
39
+ 如“(轻笑)”“(压低声音)”“(停顿)”;标签由模型按自然语言理解,不是固定词表。只在确有必要处使用,
40
+ 单个标签应短小,不把场景、心理活动或冗长指令塞进括号,也不要用标签拼出逐句声学时间表。
41
+
42
+ 语音范例只借鉴“信息完整而控制克制”的写法,绝不可把其中的人设套给别的角色:
43
+ - 官方导演模式范例(压缩为本工具字段):管理页角色为“百年门阀的现任掌事者,克制、疏离”;
44
+ `scene`:“在祠堂里,看着男人突破阻拦来找她、想带她离开;她要用冷硬态度逼对方退却,也压住自己刚萌芽的感情。”;
45
+ `direction`:“以松弛、冷静而有威压的状态说话,表面的疏离下保留克制的疲惫与动摇。”
46
+ - 已验证的雪雪范例:管理页角色为“雪雪,成年男性;外形的声音都偏中性化,可爱的正太音”;
47
+ `scene`:“因哥哥不告而别且没有好好吃饭而生气,嘴硬地训人,最后又舍不得继续凶。”;
48
+ `direction`:“自然表现出从生气到心软的情绪转折,在适当的地方改变语气和语调。务必注意咬字清晰。”
49
+ 为其它角色创作时,按同样粒度重写与当前台词相符的场景和指导,不复制示例人物、事件或固定措辞。
33
50
 
34
51
  # 第二章 · 角色认知与对话流程
35
52
 
@@ -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
- else if (rebuild) {
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
  }
@@ -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 : []) push('character', ev.time, m);
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']);
@@ -175,17 +176,31 @@ export function buildDirectorToolDefs(resolveCtx) {
175
176
  + '就填一个较短的间隔,比如 3 到 10 分钟;如果你们约定了某个具体的时刻再继续,比如'
176
177
  + '“中午再聊”,就把分钟数直接算到那个时刻,距离中午还有 3 个小时就填 180;如果只是平时'
177
178
  + '自然地把话题搁一搁,填一个适中的间隔即可。'
178
- + 'messages 为空数组时可只安排 reawake 而本次不发。'
179
- + '只允许发送拟真的、贴合角色性格的聊天文本;绝不发送思考、计划、动作描述、工具说明或任何非消息内容。'
180
- + '如果你决定此刻不打扰对方,就不要调用本工具。',
179
+ + 'messages 为空数组时可只安排 reawake 而本次不发。'
180
+ + '只允许发送拟真的、贴合角色性格的聊天文本;绝不发送思考、计划、动作描述、工具说明或任何非消息内容。'
181
+ + '语音项仅在更适合当下表达时使用:text 是原样朗读的台词;scene 写清当前事件、对象和人物动机;direction 只给一句整段成立的表演意图。'
182
+ + '角色音色身份已经由管理页配置,不要在语音项重复。禁止用“前面/中段/后面”等模糊时序词、逐句声学控制、旁白或台词外心理活动。'
183
+ + 'text 可保留或加入简短中文圆括号语义标签,例如“(轻笑)”“(压低声音)”“(停顿)”;这类标签按自然语言理解,并非固定词表。仅在确有必要处使用,单个标签要短,不把场景、心理活动或长指令塞进括号,也不以标签编排逐句变化。'
184
+ + '写法参考一(官方导演模式的压缩范例):管理页角色为克制疏离的门阀掌事者;scene 为“祠堂中拒绝想带她离开的男人,也压住刚萌芽的感情”;direction 为“松弛、冷静而有威压,疏离下保留克制的疲惫与动摇”。'
185
+ + '写法参考二(雪雪已验证范例):管理页角色为中性可爱的成年男性;scene 为“哥哥不告而别且没有好好吃饭,嘴硬地训人又舍不得继续凶”;direction 为“自然表现出从生气到心软的情绪转折,在适当的地方改变语气和语调。务必注意咬字清晰”。'
186
+ + '只学习二者的完整情境与克制指导,不得复制其人物、事件或措辞。'
187
+ + '如果你决定此刻不打扰对方,就不要调用本工具。',
181
188
  parameters: {
182
189
  type: 'object',
183
190
  additionalProperties: false,
184
191
  properties: {
185
- messages: {
186
- type: 'array',
187
- items: { type: 'string' },
188
- description: '要逐条发送的聊天消息列表;空数组或省略 = 不发送(沉默)。',
192
+ messages: {
193
+ type: 'array',
194
+ items: { oneOf: [
195
+ { type: 'string' },
196
+ { type: 'object', additionalProperties: false, required: ['type', 'text'], properties: {
197
+ type: { type: 'string', enum: ['text', 'voice'] },
198
+ text: { type: 'string', description: '发送文本或朗读台词;语音台词允许少量简短圆括号语义标签,如“(轻笑)”,不使用冗长标签。' },
199
+ scene: { type: 'string', description: '仅 voice:本条语音的完整情景、对话对象与情绪动机;不要重复管理页角色设定。' },
200
+ direction: { type: 'string', description: '仅 voice:一句整体表演方向;不编排逐句变化时机,不写模糊时序词或旁白。简短语义标签仅可放在 text 中。' },
201
+ } },
202
+ ] },
203
+ description: '按顺序发送的消息;字符串兼容旧文本格式。voice 由角色已配置的 MiMo 音色合成并发送。空数组或省略 = 不发送。',
189
204
  },
190
205
  reawake: {
191
206
  oneOf: [{ type: 'number' }, { type: 'string' }],
@@ -204,7 +219,7 @@ export function buildDirectorToolDefs(resolveCtx) {
204
219
  schema: {
205
220
  type: 'object',
206
221
  additionalProperties: false,
207
- properties: { ok: { type: 'boolean' }, sent: { type: 'number' }, reawake: { type: 'number' }, error: { type: 'string' } },
222
+ properties: { ok: { type: 'boolean' }, sent: { type: 'number' }, textSent: { type: 'number' }, voiceSent: { type: 'number' }, failedAt: { type: 'number' }, reawake: { type: 'number' }, error: { type: 'string' } },
208
223
  required: ['ok', 'sent'],
209
224
  },
210
225
  render: (_args, value) => [
@@ -213,32 +228,42 @@ export function buildDirectorToolDefs(resolveCtx) {
213
228
  : `发送失败: ${value.error ?? '?'}` },
214
229
  ],
215
230
  },
216
- timeoutMs: 60_000,
231
+ timeoutMs: 360_000,
217
232
  async execute(args, exec) {
218
233
  const c = await resolveCtx(args, exec);
219
- const raw = Array.isArray(args?.messages) ? args.messages : [];
220
- const messages = raw.map((s) => String(s ?? '').trim()).filter((s) => s.length > 0);
221
- const sent = [];
234
+ const raw = Array.isArray(args?.messages) ? args.messages : [];
235
+ const messages = raw.map((item) => typeof item === 'string'
236
+ ? { type: 'text', text: item.trim() }
237
+ : { type: item?.type === 'voice' ? 'voice' : 'text', text: String(item?.text ?? '').trim(), scene: String(item?.scene ?? '').trim(), direction: String(item?.direction ?? '').trim() })
238
+ .filter((item) => item.text.length > 0);
239
+ const sent = [];
222
240
  if (messages.length > 0) {
223
241
  const record = c.routes?.get(c.sessionId);
224
242
  const passive = record
225
243
  ? c.routes.consumePassive(c.sessionId, record.target.kind === 'group' ? 5 * 60 * 1000 : 30 * 60 * 1000, 4)
226
244
  : undefined;
227
- for (const msg of messages) {
228
- try {
229
- await c.api.sendText(c.target(), msg, passive);
230
- sent.push(msg);
245
+ for (const msg of messages) {
246
+ try {
247
+ if (msg.type === 'voice') {
248
+ if (!c.roleId) throw new Error('当前会话没有角色语音配置');
249
+ const audio = await synthesizeMiMoVoice({ roleId: c.roleId, text: msg.text, scene: msg.scene, direction: msg.direction });
250
+ try { await c.api.sendMedia(c.target(), 'voice', audio.file, { passiveMsgId: passive }); }
251
+ finally { await audio.cleanup(); }
252
+ } else {
253
+ await c.api.sendText(c.target(), msg.text, passive);
254
+ }
255
+ sent.push(msg);
231
256
  }
232
257
  catch (error) {
233
258
  return {
234
- ok: false, sent: sent.length,
259
+ ok: false, sent: sent.length, failedAt: sent.length,
235
260
  error: error instanceof Error ? error.message : String(error),
236
261
  };
237
262
  }
238
263
  }
239
264
  // 日期层记忆:角色消息发出后延迟从活跃会话 session log 提取写原始记录
240
265
  // (等 dsh 把 director_send 工具调用落盘;仅 c2c 拥有者会话)。
241
- if (sent.length > 0 && c.target()?.kind === 'c2c') {
266
+ if (sent.length > 0 && c.target()?.kind === 'c2c') {
242
267
  const workspace = c.workspaceOf
243
268
  ? await c.workspaceOf()
244
269
  : (c.persona && c.roleId ? c.persona.roleWorkspace(c.roleId) : undefined);
@@ -258,7 +283,7 @@ export function buildDirectorToolDefs(resolveCtx) {
258
283
  // reawake:正数分钟 → 写角色 state.rewake 队列;'none'/缺省 → 不安排。
259
284
  const ra = args?.reawake;
260
285
  if (ra === undefined || ra === null || ra === 'none' || ra === 'NONE')
261
- return { ok: true, sent: sent.length };
286
+ return { ok: true, sent: sent.length, textSent: sent.filter((m) => m.type === 'text').length, voiceSent: sent.filter((m) => m.type === 'voice').length };
262
287
  const minutes = typeof ra === 'number' ? ra : Number(String(ra).trim());
263
288
  if (Number.isFinite(minutes) && minutes > 0) {
264
289
  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
+ }