pygmalion 0.1.14 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +141 -69
- package/THIRD_PARTY.md +9 -0
- package/docs/ARCHITECTURE.md +66 -107
- package/docs/DEPLOY.md +33 -136
- package/docs/DEVELOPMENT.md +63 -0
- package/docs/DEVICE.md +56 -47
- package/docs/EXTENSIONS.md +176 -0
- package/docs/PRESET.md +21 -63
- package/docs/UPGRADE-0.2.md +52 -0
- package/package.json +52 -33
- package/preset/pygmalion-director/cordis.patch.yml +234 -0
- package/preset/pygmalion-director/pygmalion-tools.js +43 -41
- package/scripts/start-local-test.mjs +45 -45
- package/skills/pygmalion-life-scripts/SKILL.md +12 -0
- package/skills/pygmalion-meme-maintenance/SKILL.md +12 -0
- package/skills/pygmalion-memory-archive/SKILL.md +24 -0
- package/skills/pygmalion-toy-control/SKILL.md +16 -0
- package/src/agent-life.js +608 -606
- package/src/archive-tools.js +9 -0
- package/src/bot-factory.js +129 -306
- package/src/bots.js +264 -275
- package/src/channel-qq.js +262 -0
- package/src/config.js +69 -68
- package/src/delivery-receipt.js +36 -0
- package/src/delivery-scope.js +20 -0
- package/src/devices/manager.mjs +80 -525
- package/src/devices/monsterparty-controller.mjs +393 -0
- package/src/devices/{doc.mjs → monsterparty-doc.mjs} +60 -69
- package/src/devices/monsterparty.mjs +294 -294
- package/src/devices/pb.mjs +110 -110
- package/src/devices/registry.mjs +19 -0
- package/src/devices/script-helper.mjs +45 -0
- package/src/devices/scripts.mjs +109 -0
- package/src/devices/service.mjs +254 -0
- package/src/director-messages.js +35 -0
- package/src/dsh-runtime.js +17 -0
- package/src/extension-config.js +20 -0
- package/src/extensions.js +118 -0
- package/src/heartbeat.js +117 -95
- package/src/http-api.js +519 -509
- package/src/inbound.js +36 -207
- package/src/index.js +109 -37
- package/src/llm-provider.js +214 -171
- package/src/meme-worker.js +35 -39
- package/src/memebox.js +1 -1
- package/src/memory-recall.js +55 -0
- package/src/memory-write.js +136 -133
- package/src/peer-identity.js +26 -0
- package/src/persona.js +120 -41
- package/src/role-agent.js +155 -0
- package/src/role-runtime.js +65 -0
- package/src/roleplay-config.js +37 -0
- package/src/roleplay-format.js +37 -0
- package/src/roleplay-generation.js +36 -0
- package/src/roleplay-materials.js +113 -0
- package/src/roleplay-output.js +19 -0
- package/src/roleplay-parallel.js +239 -0
- package/src/roleplay-session.js +128 -0
- package/src/roleplay-worker.js +10 -0
- package/src/session-log.js +180 -143
- package/src/setup-agent.js +92 -100
- package/src/skills.js +97 -0
- package/src/slash-commands.js +155 -142
- package/src/speech-input.js +20 -0
- package/src/threads.js +2 -1
- package/src/tools.js +216 -168
- package/src/voice-defaults.js +13 -0
- package/src/voice-mimo.js +139 -95
- package/src/voice.js +200 -0
- package/src/wakeup.js +76 -35
- package/src/web-public/app.js +536 -367
- package/src/web-public/index.html +161 -156
- package/src/web-public/layout.css +7 -7
- package/src/web-public/style.css +12 -8
- package/src/web-server.js +158 -89
- package/src/worker-tools.js +18 -0
- package/templates/sample-life.mjs +59 -59
- package/templates/sample-toy.mjs +33 -33
- package/preset/pygmalion-director/agent.cordis.yml +0 -253
- package/preset/pygmalion-director/preset.yml +0 -3
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** 内置实现接线;通用语音服务不依赖任何厂商。 */
|
|
2
|
+
import * as persona from './persona.js';
|
|
3
|
+
import { createExtensionRegistry } from './extensions.js';
|
|
4
|
+
import { createVoiceService } from './voice.js';
|
|
5
|
+
import { mimoTtsProvider } from './voice-mimo.js';
|
|
6
|
+
|
|
7
|
+
export function createBundledVoiceServices(options = {}) {
|
|
8
|
+
const extensions = options.extensions ?? createExtensionRegistry();
|
|
9
|
+
extensions.registerTtsProvider(mimoTtsProvider);
|
|
10
|
+
const voice = createVoiceService({ extensions, persona: options.persona ?? persona,
|
|
11
|
+
defaultProviderId: 'mimo', ...options });
|
|
12
|
+
return { extensions, voice };
|
|
13
|
+
}
|
package/src/voice-mimo.js
CHANGED
|
@@ -1,95 +1,139 @@
|
|
|
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
|
-
|
|
9
|
-
|
|
10
|
-
const
|
|
11
|
-
const
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
apiKey:
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
await
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
const
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
const
|
|
90
|
-
|
|
91
|
-
const
|
|
92
|
-
const
|
|
93
|
-
|
|
94
|
-
|
|
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
|
+
export { VoiceSynthesisTimeoutError, isVoiceSynthesisTimeout } from './voice.js';
|
|
8
|
+
import { VoiceSynthesisTimeoutError } from './voice.js';
|
|
9
|
+
|
|
10
|
+
const BASE = 'https://api.xiaomimimo.com/v1';
|
|
11
|
+
const MODEL = 'mimo-v2.5-tts-voiceclone';
|
|
12
|
+
const MAX_REFERENCE_BYTES = Math.floor((10 * 1024 * 1024 * 3) / 4);
|
|
13
|
+
const FALLBACK = '请保持咬字清晰。情绪、语气、声调和音量应依据角色、场景和台词自然、连贯地变化。';
|
|
14
|
+
const MIN_TTS_TIMEOUT_MS = 45_000;
|
|
15
|
+
const MAX_TTS_TIMEOUT_MS = 300_000;
|
|
16
|
+
|
|
17
|
+
function voiceDir(roleId) { return join(persona.roleDir(roleId), 'voice'); }
|
|
18
|
+
function configPath(roleId) { return join(voiceDir(roleId), 'mimo.json'); }
|
|
19
|
+
function referencePath(roleId, ext = 'wav') { return join(voiceDir(roleId), `reference.${ext}`); }
|
|
20
|
+
function clean(value, max = 2000) { return String(value ?? '').trim().slice(0, max); }
|
|
21
|
+
|
|
22
|
+
/** 短台词不无止境等待,长台词按字符数留出更多合成时间。 */
|
|
23
|
+
export function voiceTimeoutMs(text) {
|
|
24
|
+
const length = [...String(text ?? '').trim()].length;
|
|
25
|
+
return Math.min(MAX_TTS_TIMEOUT_MS, Math.max(MIN_TTS_TIMEOUT_MS, 30_000 + length * 900));
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export async function loadVoiceConfig(roleId) {
|
|
29
|
+
const role = await persona.loadRole(roleId);
|
|
30
|
+
if (!role) return null;
|
|
31
|
+
const value = await readFile(configPath(roleId), 'utf8').then(JSON.parse).catch(() => ({}));
|
|
32
|
+
const ref = value.reference && existsSync(referencePath(roleId, value.reference.ext)) ? value.reference : null;
|
|
33
|
+
return { enabled: value.enabled === true, apiBase: clean(value.apiBase) || BASE, model: clean(value.model) || MODEL,
|
|
34
|
+
apiKey: clean(value.apiKey, 500), rolePrompt: clean(value.rolePrompt), reference: ref };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export async function saveVoiceConfig(roleId, patch) {
|
|
38
|
+
const current = await loadVoiceConfig(roleId);
|
|
39
|
+
if (!current) throw new Error('角色不存在');
|
|
40
|
+
const next = {
|
|
41
|
+
enabled: patch?.enabled === undefined ? current.enabled : patch.enabled === true,
|
|
42
|
+
apiBase: clean(patch?.apiBase) || current.apiBase || BASE,
|
|
43
|
+
model: clean(patch?.model) || current.model || MODEL,
|
|
44
|
+
apiKey: patch?.apiKey === undefined || clean(patch.apiKey, 500) === '' ? current.apiKey : clean(patch.apiKey, 500),
|
|
45
|
+
rolePrompt: patch?.rolePrompt === undefined ? current.rolePrompt : clean(patch.rolePrompt),
|
|
46
|
+
reference: current.reference,
|
|
47
|
+
};
|
|
48
|
+
await mkdir(voiceDir(roleId), { recursive: true });
|
|
49
|
+
await persona.atomicWrite(configPath(roleId), JSON.stringify(next, null, 2));
|
|
50
|
+
return publicVoiceConfig(next);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export async function saveReferenceAudio(roleId, { data, mime, name }) {
|
|
54
|
+
const cfg = await loadVoiceConfig(roleId);
|
|
55
|
+
if (!cfg) throw new Error('角色不存在');
|
|
56
|
+
const normalized = String(mime ?? '').toLowerCase();
|
|
57
|
+
const ext = normalized === 'audio/mpeg' || normalized === 'audio/mp3' ? 'mp3' : normalized === 'audio/wav' || normalized === 'audio/x-wav' ? 'wav' : null;
|
|
58
|
+
if (!ext) throw new Error('参考音频只支持 WAV 或 MP3');
|
|
59
|
+
const bytes = Buffer.from(String(data ?? ''), 'base64');
|
|
60
|
+
if (!bytes.length || bytes.length > MAX_REFERENCE_BYTES) throw new Error('参考音频过大(Base64 编码后不得超过 10MB)');
|
|
61
|
+
await mkdir(voiceDir(roleId), { recursive: true });
|
|
62
|
+
if (cfg.reference?.ext && cfg.reference.ext !== ext) await rm(referencePath(roleId, cfg.reference.ext), { force: true });
|
|
63
|
+
await writeFile(referencePath(roleId, ext), bytes);
|
|
64
|
+
const next = { ...cfg, reference: { ext, name: clean(name, 180) || `reference.${ext}`, bytes: bytes.length, updatedAt: Date.now() } };
|
|
65
|
+
await persona.atomicWrite(configPath(roleId), JSON.stringify(next, null, 2));
|
|
66
|
+
return publicVoiceConfig(next);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function publicVoiceConfig(config) {
|
|
70
|
+
return { enabled: config?.enabled === true, configured: Boolean(config?.apiKey), apiBase: config?.apiBase || BASE,
|
|
71
|
+
model: config?.model || MODEL, rolePrompt: config?.rolePrompt || '', reference: config?.reference || null };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function buildVoiceDirectorPrompt({ rolePrompt, scene, direction }) {
|
|
75
|
+
return [`角色:${clean(rolePrompt, 1200) || '保持参考音频中的角色音色。'}`,
|
|
76
|
+
`场景:${clean(scene, 1600) || '根据台词自然表达。'}`,
|
|
77
|
+
`指导:${clean(direction, 800) || '自然表达当前情绪。'}`,
|
|
78
|
+
FALLBACK].join('\n');
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export async function synthesizeMiMoVoice({ roleId, text, scene, direction, signal, config, readReference }) {
|
|
82
|
+
const cfg = config ?? await loadVoiceConfig(roleId);
|
|
83
|
+
if (!cfg?.enabled) throw new Error('该角色未启用 MiMo 语音');
|
|
84
|
+
if (!cfg.apiKey) throw new Error('该角色尚未配置 MiMo API Key');
|
|
85
|
+
if (!cfg.reference) throw new Error('该角色尚未上传参考音频');
|
|
86
|
+
const spoken = String(text ?? '');
|
|
87
|
+
if (!spoken.trim()) throw new Error('语音台词不能为空');
|
|
88
|
+
if ([...spoken].length > 5000) throw new Error('MiMo 单次台词超过 5000 字符,请明确分段后发送');
|
|
89
|
+
const reference = readReference ? await readReference() : await readFile(referencePath(roleId, cfg.reference.ext));
|
|
90
|
+
const mime = cfg.reference.mediaType ?? (cfg.reference.ext === 'mp3' ? 'audio/mpeg' : 'audio/wav');
|
|
91
|
+
const timeoutMs = voiceTimeoutMs(spoken);
|
|
92
|
+
const timeoutSignal = AbortSignal.timeout(timeoutMs);
|
|
93
|
+
const requestSignal = signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;
|
|
94
|
+
try {
|
|
95
|
+
const res = await fetch(`${cfg.apiBase.replace(/\/$/, '')}/chat/completions`, {
|
|
96
|
+
method: 'POST', headers: { authorization: `Bearer ${cfg.apiKey}`, 'content-type': 'application/json' },
|
|
97
|
+
body: JSON.stringify({ model: cfg.model, messages: [
|
|
98
|
+
{ role: 'user', content: buildVoiceDirectorPrompt({ rolePrompt: cfg.rolePrompt, scene, direction }) },
|
|
99
|
+
{ role: 'assistant', content: spoken },
|
|
100
|
+
], audio: { format: 'wav', voice: `data:${mime};base64,${reference.toString('base64')}` } }),
|
|
101
|
+
signal: requestSignal,
|
|
102
|
+
});
|
|
103
|
+
const raw = await res.text(); let json; try { json = JSON.parse(raw); } catch { json = {}; }
|
|
104
|
+
const audio = json?.choices?.[0]?.message?.audio?.data;
|
|
105
|
+
if (!res.ok || typeof audio !== 'string') throw new Error(`MiMo 合成失败(HTTP ${res.status}):${json?.error?.message || json?.message || '无音频返回'}`);
|
|
106
|
+
const dir = await mkdtemp(join(tmpdir(), 'pygmalion-mimo-'));
|
|
107
|
+
const file = join(dir, 'voice.wav');
|
|
108
|
+
try { await writeFile(file, Buffer.from(audio, 'base64')); }
|
|
109
|
+
catch (error) { await rm(dir, { recursive: true, force: true }); throw error; }
|
|
110
|
+
return { file, mediaType: 'audio/wav', cleanup: () => rm(dir, { recursive: true, force: true }) };
|
|
111
|
+
} catch (error) {
|
|
112
|
+
if (timeoutSignal.aborted && !signal?.aborted) throw new VoiceSynthesisTimeoutError(timeoutMs);
|
|
113
|
+
throw error;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** 克隆及参考素材属于内置实现;普通 TTS 不需要这些字段。 */
|
|
118
|
+
export const mimoTtsProvider = {
|
|
119
|
+
apiVersion: 1, id: 'mimo', name: 'MiMo 音色克隆',
|
|
120
|
+
fields: [
|
|
121
|
+
{ key: 'apiBase', label: 'API 地址', type: 'text', default: BASE, required: true },
|
|
122
|
+
{ key: 'model', label: '模型', type: 'text', default: MODEL, required: true },
|
|
123
|
+
{ key: 'apiKey', label: 'API Key', type: 'secret', required: true },
|
|
124
|
+
{ key: 'rolePrompt', label: '角色语音设定', type: 'text' },
|
|
125
|
+
{ key: 'reference', label: '参考音频', type: 'audio', required: true,
|
|
126
|
+
accept: ['audio/wav', 'audio/mpeg'], maxBytes: MAX_REFERENCE_BYTES },
|
|
127
|
+
],
|
|
128
|
+
capabilities: { instructions: true, inlinePerformanceTags: true },
|
|
129
|
+
async loadLegacy(roleId) {
|
|
130
|
+
const config = await loadVoiceConfig(roleId);
|
|
131
|
+
if (!config) return {};
|
|
132
|
+
return { ...config, reference: config.reference ? { ...config.reference,
|
|
133
|
+
file: `reference.${config.reference.ext}`, mediaType: config.reference.ext === 'mp3' ? 'audio/mpeg' : 'audio/wav' } : null };
|
|
134
|
+
},
|
|
135
|
+
create({ roleId, config, readAsset }) {
|
|
136
|
+
return { synthesize: request => synthesizeMiMoVoice({ ...request, roleId,
|
|
137
|
+
config: { ...config, enabled: true }, readReference: () => readAsset(config.reference) }) };
|
|
138
|
+
},
|
|
139
|
+
};
|
package/src/voice.js
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import { defaults, validate } from './extension-config.js';
|
|
2
|
+
/** 角色语音服务:配置与资源归属在宿主,音色语义和合成在 provider。 */
|
|
3
|
+
import { mkdir, readFile, writeFile, mkdtemp, rm, stat, realpath } from 'node:fs/promises';
|
|
4
|
+
import { join, resolve, relative, isAbsolute } from 'node:path';
|
|
5
|
+
import { tmpdir } from 'node:os';
|
|
6
|
+
import { randomUUID } from 'node:crypto';
|
|
7
|
+
|
|
8
|
+
/** 常见容器的基本格式识别;不依赖文件名或浏览器给出的 MIME。 */
|
|
9
|
+
function audioFormat(bytes) {
|
|
10
|
+
const tag = bytes.toString('ascii', 0, 4);
|
|
11
|
+
if (tag === 'RIFF' && bytes.toString('ascii', 8, 12) === 'WAVE') return { mediaType: 'audio/wav', ext: 'wav' };
|
|
12
|
+
if (tag === 'OggS') return { mediaType: 'audio/ogg', ext: 'ogg' };
|
|
13
|
+
if (tag === 'fLaC') return { mediaType: 'audio/flac', ext: 'flac' };
|
|
14
|
+
if (bytes.toString('ascii', 4, 8) === 'ftyp') return { mediaType: 'audio/mp4', ext: 'm4a' };
|
|
15
|
+
if (bytes[0] === 0xff && (bytes[1] & 0xf6) === 0xf0) return { mediaType: 'audio/aac', ext: 'aac' };
|
|
16
|
+
if (bytes.toString('ascii', 0, 3) === 'ID3' || bytes[0] === 0xff && (bytes[1] & 0xe0) === 0xe0) return { mediaType: 'audio/mpeg', ext: 'mp3' };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export class VoiceSynthesisTimeoutError extends Error {
|
|
20
|
+
constructor(timeoutMs) {
|
|
21
|
+
super(`语音合成超时(等待 ${Math.ceil(timeoutMs / 1000)} 秒)`);
|
|
22
|
+
this.name = 'VoiceSynthesisTimeoutError';
|
|
23
|
+
this.code = 'TTS_TIMEOUT'; this.timeoutMs = timeoutMs;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
export const isVoiceSynthesisTimeout = error => error?.code === 'TTS_TIMEOUT';
|
|
27
|
+
|
|
28
|
+
/** 只提供能力事实,同一说明用于主会话和角色编写会话。 */
|
|
29
|
+
export function voiceCapabilityNotice(view) {
|
|
30
|
+
if (!view.ready) return `当前语音不可用:${view.reason || '尚未启用'}。`;
|
|
31
|
+
return `当前语音可用。场景/表演指导:${view.capabilities.instructions ? '支持' : '不支持,仅朗读台词'}。`
|
|
32
|
+
+ `括号表演标签:${view.capabilities.inlinePerformanceTags ? '支持,可少量使用' : '不支持,不要将表演指令写入台词'}。`;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function createVoiceService({ extensions, persona, defaultProviderId, timeoutMs = 300_000 }) {
|
|
36
|
+
const queues = new Map();
|
|
37
|
+
const lifetime = new AbortController();
|
|
38
|
+
const dir = roleId => join(persona.roleDir(roleId), 'voice');
|
|
39
|
+
async function load(roleId) {
|
|
40
|
+
if (!await persona.loadRole(roleId)) throw new Error('角色不存在');
|
|
41
|
+
let saved;
|
|
42
|
+
try { saved = JSON.parse(await readFile(join(dir(roleId), 'config.json'), 'utf8')); }
|
|
43
|
+
catch (error) { if (error.code !== 'ENOENT') throw new Error('语音配置不可读'); }
|
|
44
|
+
const providerId = saved?.providerId ?? defaultProviderId;
|
|
45
|
+
const descriptor = extensions.getTtsProvider(providerId)?.descriptor;
|
|
46
|
+
const legacy = saved ? {} : await descriptor?.loadLegacy?.(roleId) ?? {};
|
|
47
|
+
const values = saved?.profiles?.[providerId] ?? legacy;
|
|
48
|
+
return { providerId, enabled: saved ? saved.enabled === true : legacy.enabled === true,
|
|
49
|
+
revision: saved?.revision ?? 0, profiles: saved?.profiles ?? {}, values: descriptor ? defaults(descriptor, values) : values };
|
|
50
|
+
}
|
|
51
|
+
function serialize(roleId, action) {
|
|
52
|
+
const pending = (queues.get(roleId) ?? Promise.resolve()).catch(() => {}).then(action);
|
|
53
|
+
queues.set(roleId, pending);
|
|
54
|
+
return pending.finally(() => { if (queues.get(roleId) === pending) queues.delete(roleId); });
|
|
55
|
+
}
|
|
56
|
+
async function view(roleId, providerId) {
|
|
57
|
+
let state;
|
|
58
|
+
try { state = await load(roleId); }
|
|
59
|
+
catch { return { providerId: '', enabled: false, ready: false, configured: false,
|
|
60
|
+
reason: '语音配置不可读,原文件已保留', revision: 0, values: {}, secrets: {}, fields: [], capabilities: {} }; }
|
|
61
|
+
if (providerId && providerId !== state.providerId) {
|
|
62
|
+
const descriptor = extensions.getTtsProvider(providerId)?.descriptor;
|
|
63
|
+
state = { ...state, providerId, values: descriptor ? defaults(descriptor, state.profiles[providerId] ?? {}) : {} };
|
|
64
|
+
}
|
|
65
|
+
const descriptor = extensions.getTtsProvider(state.providerId)?.descriptor;
|
|
66
|
+
let reason = descriptor ? '' : '所选语音扩展不可用';
|
|
67
|
+
if (descriptor) { try { validate(descriptor, state.values, true); } catch (error) { reason = error.message; } }
|
|
68
|
+
const values = {}, secrets = {};
|
|
69
|
+
for (const field of descriptor?.fields ?? []) {
|
|
70
|
+
const value = state.values[field.key];
|
|
71
|
+
if (field.type === 'secret') secrets[field.key] = Boolean(value);
|
|
72
|
+
else if (value !== undefined && value !== null) values[field.key] = field.type === 'audio'
|
|
73
|
+
? { name: value.name, bytes: value.bytes, mediaType: value.mediaType } : value;
|
|
74
|
+
}
|
|
75
|
+
let declared;
|
|
76
|
+
try { declared = typeof descriptor?.capabilities === 'function' ? descriptor.capabilities(state.values) : descriptor?.capabilities; }
|
|
77
|
+
catch { reason ||= '语音能力说明不可用'; }
|
|
78
|
+
const capabilities = { instructions: declared?.instructions === true, inlinePerformanceTags: declared?.inlinePerformanceTags === true };
|
|
79
|
+
return { providerId: state.providerId, enabled: state.enabled, revision: state.revision,
|
|
80
|
+
configured: !reason, ready: state.enabled && !reason, reason, values, secrets,
|
|
81
|
+
fields: descriptor?.fields ?? [], capabilities };
|
|
82
|
+
}
|
|
83
|
+
async function save(roleId, patch, upload) {
|
|
84
|
+
return serialize(roleId, async () => {
|
|
85
|
+
const state = await load(roleId);
|
|
86
|
+
if (patch.revision !== undefined && patch.revision !== state.revision) throw new Error('语音配置已更新,请重新加载后保存');
|
|
87
|
+
const providerId = patch.providerId ?? state.providerId;
|
|
88
|
+
const descriptor = extensions.getTtsProvider(providerId)?.descriptor;
|
|
89
|
+
if (!descriptor) throw new Error('所选语音扩展不可用,原配置已保留');
|
|
90
|
+
const previous = providerId === state.providerId ? state.values : state.profiles[providerId] ?? {};
|
|
91
|
+
const values = defaults(descriptor, previous);
|
|
92
|
+
const input = patch.values ?? Object.fromEntries(descriptor.fields.filter(field => field.key in patch).map(field => [field.key, patch[field.key]]));
|
|
93
|
+
if (!input || typeof input !== 'object' || Array.isArray(input)) throw new Error('语音配置必须是对象');
|
|
94
|
+
for (const [key, value] of Object.entries(input)) {
|
|
95
|
+
const field = descriptor.fields.find(item => item.key === key);
|
|
96
|
+
if (!field) throw new Error(`未知语音字段:${key}`);
|
|
97
|
+
if (field.type === 'audio' && value !== null && !upload) throw new Error('音频需通过上传入口设置');
|
|
98
|
+
if (field.type === 'secret' && value === '') continue;
|
|
99
|
+
if (value === null) delete values[key]; else values[key] = value;
|
|
100
|
+
}
|
|
101
|
+
const enabled = patch.enabled ?? state.enabled;
|
|
102
|
+
if (typeof enabled !== 'boolean') throw new Error('语音开关必须是布尔值');
|
|
103
|
+
validate(descriptor, values, enabled);
|
|
104
|
+
const profiles = { ...state.profiles, [state.providerId]: state.values, [providerId]: values };
|
|
105
|
+
await mkdir(dir(roleId), { recursive: true });
|
|
106
|
+
await persona.atomicWrite(join(dir(roleId), 'config.json'), JSON.stringify({
|
|
107
|
+
providerId, enabled, revision: state.revision + 1, profiles,
|
|
108
|
+
}, null, 2));
|
|
109
|
+
return view(roleId);
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
async function readAsset(roleId, asset) {
|
|
113
|
+
const base = await realpath(dir(roleId));
|
|
114
|
+
const file = await realpath(resolve(base, asset.file));
|
|
115
|
+
const rel = relative(base, file);
|
|
116
|
+
if (rel.startsWith('..') || isAbsolute(rel)) throw new Error('音频资源超出角色目录');
|
|
117
|
+
return readFile(file);
|
|
118
|
+
}
|
|
119
|
+
async function upload(roleId, { field = 'reference', data, mime, name, revision, providerId }) {
|
|
120
|
+
const state = await load(roleId);
|
|
121
|
+
if (providerId && providerId !== state.providerId) throw new Error('语音实现已改变,请重新加载');
|
|
122
|
+
const descriptor = extensions.getTtsProvider(state.providerId)?.descriptor;
|
|
123
|
+
const definition = descriptor?.fields.find(item => item.key === field && item.type === 'audio');
|
|
124
|
+
if (!definition) throw new Error('所选语音实现不接受此音频');
|
|
125
|
+
const bytes = Buffer.from(String(data ?? ''), 'base64');
|
|
126
|
+
if (!bytes.length || bytes.length > (definition.maxBytes ?? 8 * 1024 * 1024)) throw new Error('音频大小超出限制');
|
|
127
|
+
const detected = audioFormat(bytes);
|
|
128
|
+
if (!detected || !(definition.accept ?? [detected.mediaType]).includes(detected.mediaType)) throw new Error('音频实际格式不受支持');
|
|
129
|
+
const file = `assets/${randomUUID()}.${detected.ext}`;
|
|
130
|
+
await mkdir(join(dir(roleId), 'assets'), { recursive: true });
|
|
131
|
+
await writeFile(join(dir(roleId), file), bytes);
|
|
132
|
+
try {
|
|
133
|
+
return await save(roleId, { revision: revision ?? state.revision, providerId: state.providerId,
|
|
134
|
+
values: { [field]: { file, name: String(name ?? '参考音频').slice(0, 180), bytes: bytes.length, mediaType: detected.mediaType } } }, true);
|
|
135
|
+
} catch (error) { await rm(join(dir(roleId), file), { force: true }); throw error; }
|
|
136
|
+
}
|
|
137
|
+
async function synthesize({ roleId, text, scene, direction, signal }) {
|
|
138
|
+
const state = await load(roleId);
|
|
139
|
+
if (!state.enabled) throw new Error('该角色未启用语音');
|
|
140
|
+
const entry = extensions.getTtsProvider(state.providerId);
|
|
141
|
+
if (!entry) throw new Error('所选语音扩展不可用');
|
|
142
|
+
validate(entry.descriptor, state.values, true);
|
|
143
|
+
const timed = AbortSignal.timeout(timeoutMs);
|
|
144
|
+
const combined = AbortSignal.any([lifetime.signal, entry.signal, timed, ...(signal ? [signal] : [])]);
|
|
145
|
+
const assertCurrent = async () => {
|
|
146
|
+
combined.throwIfAborted();
|
|
147
|
+
const current = await load(roleId);
|
|
148
|
+
if (!current.enabled || current.revision !== state.revision || current.providerId !== state.providerId) throw new Error('语音配置已改变,本次合成已取消');
|
|
149
|
+
combined.throwIfAborted();
|
|
150
|
+
};
|
|
151
|
+
const operation = (async () => {
|
|
152
|
+
let engine, audio, temp;
|
|
153
|
+
let cleaned = false, engineDisposed = false;
|
|
154
|
+
const disposeEngine = async () => {
|
|
155
|
+
if (!engine || engineDisposed) return;
|
|
156
|
+
engineDisposed = true; await engine.dispose?.();
|
|
157
|
+
};
|
|
158
|
+
const abortEngine = () => { void disposeEngine().catch(() => {}); };
|
|
159
|
+
const cleanup = async () => {
|
|
160
|
+
if (cleaned) return; cleaned = true;
|
|
161
|
+
combined.removeEventListener('abort', abortEngine);
|
|
162
|
+
try { await audio?.cleanup?.(); }
|
|
163
|
+
finally { try { await disposeEngine(); } finally { if (temp) await rm(temp, { recursive: true, force: true }); } }
|
|
164
|
+
};
|
|
165
|
+
try {
|
|
166
|
+
combined.throwIfAborted();
|
|
167
|
+
engine = await entry.descriptor.create({ roleId, config: state.values, signal: combined, readAsset: asset => readAsset(roleId, asset) });
|
|
168
|
+
combined.throwIfAborted();
|
|
169
|
+
combined.addEventListener('abort', abortEngine, { once: true });
|
|
170
|
+
if (typeof engine?.synthesize !== 'function') throw new Error('语音实现缺少 synthesize');
|
|
171
|
+
const capabilities = typeof entry.descriptor.capabilities === 'function' ? entry.descriptor.capabilities(state.values) : entry.descriptor.capabilities;
|
|
172
|
+
audio = await engine.synthesize({ text, ...(capabilities?.instructions ? { scene, direction } : {}), signal: combined });
|
|
173
|
+
combined.throwIfAborted();
|
|
174
|
+
if (!audio?.mediaType?.startsWith('audio/')) throw new Error('语音实现未返回有效音频类型');
|
|
175
|
+
let file = audio.file;
|
|
176
|
+
if (!file && audio.data instanceof Uint8Array) {
|
|
177
|
+
temp = await mkdtemp(join(tmpdir(), 'pygmalion-voice-'));
|
|
178
|
+
const ext = { 'audio/mpeg': 'mp3', 'audio/wav': 'wav', 'audio/ogg': 'ogg', 'audio/flac': 'flac' }[audio.mediaType] ?? 'audio';
|
|
179
|
+
file = join(temp, `audio.${ext}`);
|
|
180
|
+
await writeFile(file, audio.data);
|
|
181
|
+
}
|
|
182
|
+
const size = file ? (await stat(file)).size : 0;
|
|
183
|
+
if (!size || size > 50 * 1024 * 1024) throw new Error('语音产物为空或超过 50MB 限制');
|
|
184
|
+
await assertCurrent();
|
|
185
|
+
return { file, mediaType: audio.mediaType, cleanup, assertCurrent };
|
|
186
|
+
} catch (error) { await cleanup().catch(() => {}); throw error; }
|
|
187
|
+
})();
|
|
188
|
+
// 不合作的实现迟到返回时仍清理,取消不会继续交付。
|
|
189
|
+
let onAbort;
|
|
190
|
+
const canceled = new Promise((_, reject) => {
|
|
191
|
+
onAbort = () => reject(timed.aborted && !signal?.aborted && !entry.signal.aborted && !lifetime.signal.aborted
|
|
192
|
+
? new VoiceSynthesisTimeoutError(timeoutMs) : combined.reason);
|
|
193
|
+
if (combined.aborted) onAbort(); else combined.addEventListener('abort', onAbort, { once: true });
|
|
194
|
+
});
|
|
195
|
+
try { return await Promise.race([operation, canceled]); }
|
|
196
|
+
catch (error) { void operation.then(asset => asset.cleanup()).catch(() => {}); throw error; }
|
|
197
|
+
finally { combined.removeEventListener('abort', onAbort); }
|
|
198
|
+
}
|
|
199
|
+
return { load, view, save, upload, synthesize, dispose: () => lifetime.abort(new Error('语音服务已关闭')) };
|
|
200
|
+
}
|