pygmalion 0.1.14 → 0.1.15
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/README.md +1 -0
- package/docs/ARCHITECTURE.md +1 -0
- package/docs/DEPLOY.md +1 -0
- package/docs/DEVICE.md +3 -3
- package/docs/PRESET.md +1 -1
- package/package.json +1 -1
- package/preset/pygmalion-director/agent.cordis.yml +36 -27
- package/src/bot-factory.js +9 -4
- package/src/devices/doc.mjs +2 -0
- package/src/devices/manager.mjs +62 -17
- package/src/heartbeat.js +6 -5
- package/src/message-review.js +276 -0
- package/src/persona.js +34 -18
- package/src/session-log.js +31 -2
- package/src/tools.js +133 -57
- package/src/voice-mimo.js +39 -9
- package/src/wakeup.js +33 -11
- package/src/web-public/app.js +15 -6
- package/src/web-public/index.html +2 -0
- package/src/web-server.js +14 -4
package/src/tools.js
CHANGED
|
@@ -8,10 +8,13 @@ import { sessionFileFor } from './active-session.js';
|
|
|
8
8
|
import { refreshRawRecordFromSession, charLabelOf } from './memory-write.js';
|
|
9
9
|
import { saveMeme, findMemes, memeFileFor, updateMeme, recordMemeUsed, downloadPageImagesToCollectDir } from './memebox.js';
|
|
10
10
|
import { resolveVisionConfig, collectAndClassify, withMemeLock, readImageBySubagent, archiveImageBySubagent, memeTrace } from './meme-worker.js';
|
|
11
|
-
import { synthesizeMiMoVoice } from './voice-mimo.js';
|
|
11
|
+
import { isVoiceSynthesisTimeout, synthesizeMiMoVoice } from './voice-mimo.js';
|
|
12
|
+
import { normalizeDirectorMessages, reviewDirectorSend, validateDirectorMessages } from './message-review.js';
|
|
12
13
|
|
|
13
14
|
const IMAGE_EXTS = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.svg', '.ico']);
|
|
14
|
-
const VOICE_EXTS = new Set(['.wav', '.mp3', '.silk', '.amr', '.ogg', '.flac', '.aac', '.m4a']);
|
|
15
|
+
const VOICE_EXTS = new Set(['.wav', '.mp3', '.silk', '.amr', '.ogg', '.flac', '.aac', '.m4a']);
|
|
16
|
+
/** sessionId → 最近一次因硬校验/审查退回而保留的 reawake.id;重试时精确替换,避免队列堆积。 */
|
|
17
|
+
const rejectedReawakeBySession = new Map();
|
|
15
18
|
|
|
16
19
|
/** dsh 工具输出要求无损 JSON(拒绝 undefined/NaN/非有限数);返回前剥掉 undefined 字段。 */
|
|
17
20
|
function noUndefined(obj) {
|
|
@@ -168,20 +171,20 @@ export function buildDirectorToolDefs(resolveCtx) {
|
|
|
168
171
|
{
|
|
169
172
|
name: 'director_send',
|
|
170
173
|
description: '让角色向当前 QQ 用户发送聊天消息(本模式的唯一发送通道)。QQ 用户在与角色交流,不是在与导演交流。'
|
|
171
|
-
+ 'messages
|
|
172
|
-
+ '
|
|
174
|
+
+ 'messages 是按顺序发送的 QQ 消息气泡,每个普通文字气泡写一个自然说出的语块。闲聊回应通常是一至两条,但没有固定条数上限;'
|
|
175
|
+
+ '主动展开确有多个连续想法的话题时可以自然地发更多条。文字通常不用逗号把多个本可独立说出的分句压成长句,停顿、转折、补充或另起一个意思时直接开始下一条;'
|
|
176
|
+
+ '不要为增加数量机械拆句,也不要为减少数量塞成长句,想说完就停。不写大段文章、markdown、动作描写、心理旁白或括号情绪标签。'
|
|
173
177
|
+ '【reawake 是默认动作】发送消息时,几乎每一次都应该同时带上 reawake 参数。'
|
|
174
|
-
+ 'reawake
|
|
178
|
+
+ 'reawake 填一个正数,表示多少分钟后若用户没有回复,系统会在到点唤醒你重新审视情境;'
|
|
175
179
|
+ '填 "none" 或省略则表示不安排。这是维持主动联系、不让关系冷掉的机制,不安排就意味着'
|
|
176
|
-
+ '
|
|
177
|
-
+ '
|
|
178
|
-
+ '
|
|
179
|
-
+ '“中午再聊”,就把分钟数直接算到那个时刻,距离中午还有 3 个小时就填 180;如果只是平时'
|
|
180
|
-
+ '自然地把话题搁一搁,填一个适中的间隔即可。'
|
|
180
|
+
+ '这轮聊完之后你将一直静默等待用户。时长应符合真实生活,考虑用户可能离开手机、双方正在做的事、明确约定、'
|
|
181
|
+
+ '届时情境是否可能变化以及连续没有回复后自然延长的等待,不套用固定区间。reason 只记录届时重新观察的情况,'
|
|
182
|
+
+ '不预写下一条消息,也不预设醒来后一定开口。'
|
|
181
183
|
+ 'messages 为空数组时可只安排 reawake 而本次不发。'
|
|
182
184
|
+ '只允许发送拟真的、贴合角色性格的聊天文本;绝不发送思考、计划、动作描述、工具说明或任何非消息内容。'
|
|
183
185
|
+ '文本与语音须像真人使用 QQ 那样随情景自然选择,既不能每条都发语音,也不能长期完全不用语音。'
|
|
184
186
|
+ '语音项的 text 是原样朗读的台词;scene 写清当前事件、对象和人物动机;direction 只给一句整段成立的表演意图。'
|
|
187
|
+
+ '语音合成按台词长度设置等待时限;若超时,系统会自动把同一台词作为文字发送,并在工具结果中明确说明。'
|
|
185
188
|
+ '角色音色身份已经由管理页配置,不要在语音项重复。禁止用“前面/中段/后面”等模糊时序词、逐句声学控制、旁白或台词外心理活动。'
|
|
186
189
|
+ '仅语音 text 可在必要处加入少量简短的中文圆括号语义标签,如“(轻笑)”“(压低声音)”“(停顿)”,供语音模型控制表演;'
|
|
187
190
|
+ '不把场景、心理活动或长指令塞进标签,也不用标签编排逐句变化。'
|
|
@@ -205,14 +208,13 @@ export function buildDirectorToolDefs(resolveCtx) {
|
|
|
205
208
|
},
|
|
206
209
|
reawake: {
|
|
207
210
|
oneOf: [{ type: 'number' }, { type: 'string' }],
|
|
208
|
-
description: '
|
|
209
|
-
+ '
|
|
210
|
-
+ '比如约好中午再聊、距离中午还有 3 个小时,就填 180;平时自然搁置则填一个适中的间隔。'
|
|
211
|
+
description: '建议默认携带。具体分钟数须按真实情境决定:考虑用户可能离开手机、双方正在做的事、明确约定、'
|
|
212
|
+
+ '届时情境是否可能变化,以及连续没有回复后自然延长的等待;不要套用固定区间。'
|
|
211
213
|
+ '填正数会登记等待队列;明确决定这轮不再续聊时才写 "none" 或省略。',
|
|
212
214
|
},
|
|
213
215
|
reason: {
|
|
214
216
|
type: 'string',
|
|
215
|
-
description: '可选:reawake
|
|
217
|
+
description: '可选:reawake 到期时需要重新观察的情境线索。不要预写下一条消息,也不要预设届时一定开口。',
|
|
216
218
|
},
|
|
217
219
|
},
|
|
218
220
|
},
|
|
@@ -220,46 +222,126 @@ export function buildDirectorToolDefs(resolveCtx) {
|
|
|
220
222
|
schema: {
|
|
221
223
|
type: 'object',
|
|
222
224
|
additionalProperties: false,
|
|
223
|
-
properties: {
|
|
225
|
+
properties: {
|
|
226
|
+
ok: { type: 'boolean' }, sent: { type: 'number' }, textSent: { type: 'number' }, voiceSent: { type: 'number' },
|
|
227
|
+
voiceTimeouts: { type: 'array', items: { type: 'number' } },
|
|
228
|
+
failedAt: { type: 'number' }, reawake: { type: 'number' }, error: { type: 'string' },
|
|
229
|
+
},
|
|
224
230
|
required: ['ok', 'sent'],
|
|
225
231
|
},
|
|
226
|
-
render: (_args, value) =>
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
232
|
+
render: (_args, value) => {
|
|
233
|
+
const timedOut = Array.isArray(value.voiceTimeouts) ? value.voiceTimeouts : [];
|
|
234
|
+
const timeoutText = timedOut.length > 0
|
|
235
|
+
? `(第 ${timedOut.join('、')} 条语音合成超时,已自动改发文字)`
|
|
236
|
+
: '';
|
|
237
|
+
return [{ type: 'text', text: value.ok
|
|
238
|
+
? `已发送 ${value.sent} 条消息${timeoutText}${value.reawake ? `,已安排 ${value.reawake} 延时唤醒` : ''}`
|
|
239
|
+
: `发送失败: ${value.error ?? '?'}${value.sent > 0 ? `(失败前已发送 ${value.sent} 条消息)` : ''}`
|
|
240
|
+
+ timeoutText + `${value.reawake ? '(有效的延时唤醒已保留)' : ''}` }];
|
|
241
|
+
},
|
|
231
242
|
},
|
|
232
243
|
timeoutMs: 360_000,
|
|
233
|
-
async execute(args, exec) {
|
|
234
|
-
const c = await resolveCtx(args, exec);
|
|
244
|
+
async execute(args, exec) {
|
|
245
|
+
const c = await resolveCtx(args, exec);
|
|
235
246
|
const raw = Array.isArray(args?.messages) ? args.messages : [];
|
|
236
|
-
const messages = raw
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
247
|
+
const messages = normalizeDirectorMessages(raw);
|
|
248
|
+
// 有效的 reawake 先登记。即使候选消息随后被硬校验或独立审查退回,关系仍有
|
|
249
|
+
// 下一次继续的可能;dsh 在当前轮重试时会用新安排覆盖它。
|
|
250
|
+
const ra = args?.reawake;
|
|
251
|
+
let reawakeAt;
|
|
252
|
+
let reawakeMinutes;
|
|
253
|
+
let scheduledReawakeId;
|
|
254
|
+
if (ra !== undefined && ra !== null && ra !== 'none' && ra !== 'NONE') {
|
|
255
|
+
const minutes = typeof ra === 'number' ? ra : Number(String(ra).trim());
|
|
256
|
+
if (!Number.isFinite(minutes) || minutes <= 0)
|
|
257
|
+
return { ok: false, sent: 0, error: 'reawake 必须是正数分钟、"none" 或省略' };
|
|
258
|
+
const replaceId = rejectedReawakeBySession.get(c.sessionId);
|
|
259
|
+
const rw = c.roleId && c.persona?.scheduleRewake
|
|
260
|
+
? await c.persona.scheduleRewake(c.roleId, minutes, typeof args?.reason === 'string' ? args.reason : '',
|
|
261
|
+
replaceId === undefined ? {} : { replaceId })
|
|
262
|
+
: { ok: false, atMs: 0, error: '无角色上下文' };
|
|
263
|
+
if (!rw.ok) return { ok: false, sent: 0, error: `reawake 安排失败: ${rw.error ?? '?'}` };
|
|
264
|
+
reawakeAt = rw.atMs;
|
|
265
|
+
reawakeMinutes = minutes;
|
|
266
|
+
rejectedReawakeBySession.delete(c.sessionId);
|
|
267
|
+
// 只有随后确实退回时才重新放入 map;正常发送保留原有“多个独立等待可并存”语义。
|
|
268
|
+
scheduledReawakeId = rw.id;
|
|
269
|
+
}
|
|
270
|
+
const withReawake = (value) => reawakeAt ? { ...value, reawake: reawakeAt } : value;
|
|
271
|
+
const hardIssues = validateDirectorMessages(raw, messages);
|
|
272
|
+
if (hardIssues.length > 0) {
|
|
273
|
+
if (scheduledReawakeId !== undefined) rejectedReawakeBySession.set(c.sessionId, scheduledReawakeId);
|
|
274
|
+
return withReawake({ ok: false, sent: 0, error: `消息未发送:${hardIssues.join(';')}` });
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// 审查器默认复用当前会话实际的 provider/model。调用故障时 fail-open;审查明确
|
|
278
|
+
// 退回时不发送,但保留上面已经登记的 reawake,避免辅助能力破坏主动连续性。
|
|
279
|
+
const role = c.roleId && c.persona?.loadRole ? await c.persona.loadRole(c.roleId) : undefined;
|
|
280
|
+
if (role && role.proactive?.messageReview?.enabled !== false && (messages.length > 0 || reawakeMinutes !== undefined)) {
|
|
281
|
+
try {
|
|
282
|
+
const review = await reviewDirectorSend({
|
|
283
|
+
llm: c.llm, agent: exec?.agent, role, messages,
|
|
284
|
+
reawake: reawakeMinutes, reason: args?.reason,
|
|
285
|
+
});
|
|
286
|
+
const reviewIssues = [];
|
|
287
|
+
if (messages.length > 0 && !review.messages.pass)
|
|
288
|
+
reviewIssues.push(...(review.messages.reasons.length
|
|
289
|
+
? review.messages.reasons : ['候选消息不符合自然 QQ 交流习惯']));
|
|
290
|
+
if (reawakeMinutes !== undefined && !review.reawake.reasonable)
|
|
291
|
+
reviewIssues.push(review.reawake.reason || 'reawake 时长不符合当前真实情境');
|
|
292
|
+
if (reviewIssues.length > 0) {
|
|
293
|
+
if (scheduledReawakeId !== undefined) rejectedReawakeBySession.set(c.sessionId, scheduledReawakeId);
|
|
294
|
+
c.log?.info?.('pygmalion: director_send 审查退回 role=%s model=%s/%s issues=%s',
|
|
295
|
+
c.roleId, review.route.provider, review.route.model, reviewIssues.join(';'));
|
|
296
|
+
return withReawake({ ok: false, sent: 0,
|
|
297
|
+
error: `发送前审查未通过,请重新判断后重试或保持沉默:${reviewIssues.join(';')}` });
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
catch (error) {
|
|
301
|
+
c.log?.warn?.('pygmalion: director_send 审查不可用,按 fail-open 放行 role=%s: %o', c.roleId, error);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
240
304
|
const sent = [];
|
|
241
|
-
|
|
305
|
+
const deliveredTypes = [];
|
|
306
|
+
const voiceTimeouts = [];
|
|
307
|
+
if (messages.length > 0) {
|
|
242
308
|
const record = c.routes?.get(c.sessionId);
|
|
243
309
|
const passive = record
|
|
244
310
|
? c.routes.consumePassive(c.sessionId, record.target.kind === 'group' ? 5 * 60 * 1000 : 30 * 60 * 1000, 4)
|
|
245
311
|
: undefined;
|
|
246
|
-
for (
|
|
312
|
+
for (let messageIndex = 0; messageIndex < messages.length; messageIndex++) {
|
|
313
|
+
const msg = messages[messageIndex];
|
|
247
314
|
try {
|
|
315
|
+
exec?.signal?.throwIfAborted?.();
|
|
248
316
|
if (msg.type === 'voice') {
|
|
249
317
|
if (!c.roleId) throw new Error('当前会话没有角色语音配置');
|
|
250
|
-
const
|
|
251
|
-
try {
|
|
252
|
-
|
|
318
|
+
const synthesizeVoice = typeof c.synthesizeVoice === 'function' ? c.synthesizeVoice : synthesizeMiMoVoice;
|
|
319
|
+
try {
|
|
320
|
+
const audio = await synthesizeVoice({ roleId: c.roleId, text: msg.text, scene: msg.scene,
|
|
321
|
+
direction: msg.direction, signal: exec?.signal });
|
|
322
|
+
try { await c.api.sendMedia(c.target(), 'voice', audio.file, { passiveMsgId: passive }); }
|
|
323
|
+
finally { await audio.cleanup(); }
|
|
324
|
+
deliveredTypes.push('voice');
|
|
325
|
+
}
|
|
326
|
+
catch (error) {
|
|
327
|
+
if (!isVoiceSynthesisTimeout(error)) throw error;
|
|
328
|
+
exec?.signal?.throwIfAborted?.();
|
|
329
|
+
await c.api.sendText(c.target(), msg.text, passive);
|
|
330
|
+
voiceTimeouts.push(messageIndex + 1);
|
|
331
|
+
deliveredTypes.push('text');
|
|
332
|
+
}
|
|
253
333
|
} else {
|
|
254
334
|
await c.api.sendText(c.target(), msg.text, passive);
|
|
335
|
+
deliveredTypes.push('text');
|
|
255
336
|
}
|
|
256
337
|
sent.push(msg);
|
|
257
|
-
}
|
|
258
|
-
catch (error) {
|
|
259
|
-
return {
|
|
338
|
+
}
|
|
339
|
+
catch (error) {
|
|
340
|
+
return withReawake({
|
|
260
341
|
ok: false, sent: sent.length, failedAt: sent.length,
|
|
261
|
-
|
|
262
|
-
|
|
342
|
+
voiceTimeouts,
|
|
343
|
+
error: error instanceof Error ? error.message : String(error),
|
|
344
|
+
});
|
|
263
345
|
}
|
|
264
346
|
}
|
|
265
347
|
// 日期层记忆:角色消息发出后延迟从活跃会话 session log 提取写原始记录
|
|
@@ -280,22 +362,12 @@ export function buildDirectorToolDefs(resolveCtx) {
|
|
|
280
362
|
}
|
|
281
363
|
}
|
|
282
364
|
}
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
if (Number.isFinite(minutes) && minutes > 0) {
|
|
290
|
-
const rw = c.roleId && c.persona?.scheduleRewake
|
|
291
|
-
? await c.persona.scheduleRewake(c.roleId, minutes, typeof args?.reason === 'string' ? args.reason : '')
|
|
292
|
-
: { ok: false, atMs: 0, error: '无角色上下文' };
|
|
293
|
-
if (!rw.ok)
|
|
294
|
-
return { ok: false, sent: sent.length, error: `reawake 安排失败: ${rw.error ?? '?'}` };
|
|
295
|
-
return { ok: true, sent: sent.length, reawake: rw.atMs };
|
|
296
|
-
}
|
|
297
|
-
return { ok: true, sent: sent.length };
|
|
298
|
-
},
|
|
365
|
+
}
|
|
366
|
+
return withReawake({ ok: true, sent: sent.length,
|
|
367
|
+
textSent: deliveredTypes.filter((type) => type === 'text').length,
|
|
368
|
+
voiceSent: deliveredTypes.filter((type) => type === 'voice').length,
|
|
369
|
+
voiceTimeouts });
|
|
370
|
+
},
|
|
299
371
|
},
|
|
300
372
|
// recollect:按需回忆(只在需要回忆/找话题时调用)
|
|
301
373
|
{
|
|
@@ -390,7 +462,8 @@ export function buildDirectorToolDefs(resolveCtx) {
|
|
|
390
462
|
+ '脚本启动时已自动预加载全局 wake(),直接调用即可(无需 import / fetch / 网络):内部经'
|
|
391
463
|
+ 'HTTP 调插件 /wakeup 端点,插件节流(默认同角色 10 分钟内至多一次)+ 撞车检测后'
|
|
392
464
|
+ '唤醒 dsh 注入 [脚本事件] 情境;是否开口、如何开口由你(导演)被唤醒后自行判断'
|
|
393
|
-
+ '
|
|
465
|
+
+ '(可以选择沉默)。wake() 的意义是让事件成为导演已经知晓的角色经历;事件被知晓后目的已经达成,'
|
|
466
|
+
+ '是否把它转化成 QQ 消息是另一项独立判断。'
|
|
394
467
|
+ '重要:唤醒消息里只包含 wake() 参数中的文本(mood/topic/reason 会注入 [脚本事件]'
|
|
395
468
|
+ '情境);脚本其它任何输出(console.log、写日志/日记文件等)都不会进入唤醒消息——'
|
|
396
469
|
+ '想让导演在唤醒时看到的情境,必须写进 wake() 参数,否则对唤醒毫无意义。'
|
|
@@ -523,7 +596,8 @@ export function buildDirectorToolDefs(resolveCtx) {
|
|
|
523
596
|
+ '"0,66"=L1~L2 区间、"0,0"=停住;也可写区间名 "L1,L2");seconds 本次操作的时长(秒)。\n'
|
|
524
597
|
+ '计时语义:到点后设备保持当前参数继续运行,系统会提醒你计时结束,可再次调用本工具调整或 stop。'
|
|
525
598
|
+ '设备无自动停止——由你决定何时停(用户要求停时必须停);停用 stop:true。\n'
|
|
526
|
-
+ '
|
|
599
|
+
+ '注意:玩具脚本运行期间,除 stop:true 外本工具不会接管控制。若要改用 toy_control 操控,必须先显式停止正在运行的脚本:'
|
|
600
|
+
+ '调用 toy_run_script 的 stop=<runId>(或单独调用 toy_control stop:true 停止脚本和设备),确认停止后再发起新的 toy_control 控制。',
|
|
527
601
|
parameters: {
|
|
528
602
|
type: 'object',
|
|
529
603
|
additionalProperties: false,
|
|
@@ -594,9 +668,11 @@ export function buildDirectorToolDefs(resolveCtx) {
|
|
|
594
668
|
+ '脚本侧只需关心设备参数:全局已预加载 toy 对象——await toy.set({ intensity, stroke }) 改变强度/行程、'
|
|
595
669
|
+ 'await toy.sleep(毫秒) 控制节奏、toy.stop() 停止;不接触任何通信细节。'
|
|
596
670
|
+ '每个玩具脚本必须在自行判断的合适位置调用 await toy.wake({ mood, topic, reason }),请导演感知脚本中的变化并决定是否开口。'
|
|
597
|
-
+ '脚本与运行日志完全透明可监管:管理台「玩具操控脚本」可查看运行状态与日志(toys/.logs/)。'
|
|
598
|
-
+ '
|
|
599
|
-
+ '
|
|
671
|
+
+ '脚本与运行日志完全透明可监管:管理台「玩具操控脚本」可查看运行状态与日志(toys/.logs/)。'
|
|
672
|
+
+ '脚本启动时会清除尚未到期的 toy_control 计时提醒,避免旧控制事件与脚本撞车。'
|
|
673
|
+
+ '脚本自然结束即终止,结束时设备保持最后的参数继续运行并优先提醒你;中途停可用 stop=runId '
|
|
674
|
+
+ '或 toy_control stop。脚本运行期间不得直接改用 toy_control 接管;若要改用,必须先显式停止该脚本并确认停止。'
|
|
675
|
+
+ '每次只有一段脚本在跑,新的脚本调用会接管旧脚本。\n'
|
|
600
676
|
+ '要先激活设备(用户发分享链接);激活后参考脚本会位于 toys/玩具脚本示例.mjs。',
|
|
601
677
|
parameters: {
|
|
602
678
|
type: 'object',
|
package/src/voice-mimo.js
CHANGED
|
@@ -9,12 +9,33 @@ const BASE = 'https://api.xiaomimimo.com/v1';
|
|
|
9
9
|
const MODEL = 'mimo-v2.5-tts-voiceclone';
|
|
10
10
|
const MAX_REFERENCE_BYTES = Math.floor((10 * 1024 * 1024 * 3) / 4);
|
|
11
11
|
const FALLBACK = '请保持咬字清晰。情绪、语气、声调和音量应依据角色、场景和台词自然、连贯地变化。';
|
|
12
|
+
const MIN_TTS_TIMEOUT_MS = 45_000;
|
|
13
|
+
const MAX_TTS_TIMEOUT_MS = 300_000;
|
|
12
14
|
|
|
13
15
|
function voiceDir(roleId) { return join(persona.roleDir(roleId), 'voice'); }
|
|
14
16
|
function configPath(roleId) { return join(voiceDir(roleId), 'mimo.json'); }
|
|
15
17
|
function referencePath(roleId, ext = 'wav') { return join(voiceDir(roleId), `reference.${ext}`); }
|
|
16
18
|
function clean(value, max = 2000) { return String(value ?? '').trim().slice(0, max); }
|
|
17
19
|
|
|
20
|
+
/** 短台词不无止境等待,长台词按字符数留出更多合成时间。 */
|
|
21
|
+
export function voiceTimeoutMs(text) {
|
|
22
|
+
const length = [...String(text ?? '').trim()].length;
|
|
23
|
+
return Math.min(MAX_TTS_TIMEOUT_MS, Math.max(MIN_TTS_TIMEOUT_MS, 30_000 + length * 900));
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export class VoiceSynthesisTimeoutError extends Error {
|
|
27
|
+
constructor(timeoutMs) {
|
|
28
|
+
super(`MiMo 语音合成超时(等待 ${Math.ceil(timeoutMs / 1000)} 秒)`);
|
|
29
|
+
this.name = 'VoiceSynthesisTimeoutError';
|
|
30
|
+
this.code = 'TTS_TIMEOUT';
|
|
31
|
+
this.timeoutMs = timeoutMs;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function isVoiceSynthesisTimeout(error) {
|
|
36
|
+
return error?.code === 'TTS_TIMEOUT' || error instanceof VoiceSynthesisTimeoutError;
|
|
37
|
+
}
|
|
38
|
+
|
|
18
39
|
export async function loadVoiceConfig(roleId) {
|
|
19
40
|
const role = await persona.loadRole(roleId);
|
|
20
41
|
if (!role) return null;
|
|
@@ -68,7 +89,7 @@ export function buildVoiceDirectorPrompt({ rolePrompt, scene, direction }) {
|
|
|
68
89
|
FALLBACK].join('\n');
|
|
69
90
|
}
|
|
70
91
|
|
|
71
|
-
export async function synthesizeMiMoVoice({ roleId, text, scene, direction }) {
|
|
92
|
+
export async function synthesizeMiMoVoice({ roleId, text, scene, direction, signal }) {
|
|
72
93
|
const cfg = await loadVoiceConfig(roleId);
|
|
73
94
|
if (!cfg?.enabled) throw new Error('该角色未启用 MiMo 语音');
|
|
74
95
|
if (!cfg.apiKey) throw new Error('该角色尚未配置 MiMo API Key');
|
|
@@ -77,14 +98,23 @@ export async function synthesizeMiMoVoice({ roleId, text, scene, direction }) {
|
|
|
77
98
|
if (!spoken) throw new Error('语音台词不能为空');
|
|
78
99
|
const reference = await readFile(referencePath(roleId, cfg.reference.ext));
|
|
79
100
|
const mime = cfg.reference.ext === 'mp3' ? 'audio/mpeg' : 'audio/wav';
|
|
80
|
-
const
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
101
|
+
const timeoutMs = voiceTimeoutMs(spoken);
|
|
102
|
+
const timeoutSignal = AbortSignal.timeout(timeoutMs);
|
|
103
|
+
const requestSignal = signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;
|
|
104
|
+
let res;
|
|
105
|
+
try {
|
|
106
|
+
res = await fetch(`${cfg.apiBase.replace(/\/$/, '')}/chat/completions`, {
|
|
107
|
+
method: 'POST', headers: { authorization: `Bearer ${cfg.apiKey}`, 'content-type': 'application/json' },
|
|
108
|
+
body: JSON.stringify({ model: cfg.model, messages: [
|
|
109
|
+
{ role: 'user', content: buildVoiceDirectorPrompt({ rolePrompt: cfg.rolePrompt, scene, direction }) },
|
|
110
|
+
{ role: 'assistant', content: spoken },
|
|
111
|
+
], audio: { format: 'wav', voice: `data:${mime};base64,${reference.toString('base64')}` } }),
|
|
112
|
+
signal: requestSignal,
|
|
113
|
+
});
|
|
114
|
+
} catch (error) {
|
|
115
|
+
if (timeoutSignal.aborted && !signal?.aborted) throw new VoiceSynthesisTimeoutError(timeoutMs);
|
|
116
|
+
throw error;
|
|
117
|
+
}
|
|
88
118
|
const raw = await res.text(); let json; try { json = JSON.parse(raw); } catch { json = {}; }
|
|
89
119
|
const audio = json?.choices?.[0]?.message?.audio?.data;
|
|
90
120
|
if (!res.ok || typeof audio !== 'string') throw new Error(`MiMo 合成失败(HTTP ${res.status}):${json?.error?.message || json?.message || '无音频返回'}`);
|
package/src/wakeup.js
CHANGED
|
@@ -12,7 +12,21 @@
|
|
|
12
12
|
import { effectiveSessionId } from './inbound.js';
|
|
13
13
|
import { targetKey } from './threads.js';
|
|
14
14
|
|
|
15
|
-
export const DEFAULT_CHAT_WINDOW_MS = 5 * 60_000;
|
|
15
|
+
export const DEFAULT_CHAT_WINDOW_MS = 5 * 60_000;
|
|
16
|
+
|
|
17
|
+
/** 当前会话日志中是否有尚未落 tool/result 的指定工具调用。 */
|
|
18
|
+
export function hasOpenToolCall(agent, toolName) {
|
|
19
|
+
const events = agent?.session?.events;
|
|
20
|
+
if (!Array.isArray(events)) return false;
|
|
21
|
+
const open = new Map();
|
|
22
|
+
for (const event of events) {
|
|
23
|
+
if (event?.type === 'tool/call' && event.data?.callId != null)
|
|
24
|
+
open.set(String(event.data.callId), event.data.name);
|
|
25
|
+
else if (event?.type === 'tool/result' && event.data?.message?.source?.callId != null)
|
|
26
|
+
open.delete(String(event.data.message.source.callId));
|
|
27
|
+
}
|
|
28
|
+
return [...open.values()].includes(toolName);
|
|
29
|
+
}
|
|
16
30
|
|
|
17
31
|
/** Human "now" used inside the wakeup context. */
|
|
18
32
|
function nowText(now = new Date()) {
|
|
@@ -157,8 +171,8 @@ export async function archiveWakeup(deps, params) {
|
|
|
157
171
|
return { ok: true, sessionId };
|
|
158
172
|
}
|
|
159
173
|
|
|
160
|
-
export async function wakeupSession(deps, params) {
|
|
161
|
-
const { target, reason, memoryHint, force, kind, event, mood, topic, contextText } = params;
|
|
174
|
+
export async function wakeupSession(deps, params) {
|
|
175
|
+
const { target, reason, memoryHint, force, kind, event, mood, topic, contextText, interruptTool } = params;
|
|
162
176
|
const thread = deps.threads.current(targetKey(target));
|
|
163
177
|
const sessionId = effectiveSessionId(target, thread, deps.botId);
|
|
164
178
|
|
|
@@ -199,15 +213,23 @@ export async function wakeupSession(deps, params) {
|
|
|
199
213
|
if (typeof contextText === 'string' && contextText.length > 0) {
|
|
200
214
|
text = contextText; // 调用方已构造完整情境(如设备事件)
|
|
201
215
|
} else if (kind === 'life') text = buildLifeWindowContext({ reason, personaName, hasLifeScript });
|
|
202
|
-
else if (kind === 'script-hook') text = buildScriptEventContext({ event, mood, topic, reason, personaName });
|
|
203
|
-
else text = buildWakeupContext({ reason, memoryHint, personaName });
|
|
204
|
-
deps.log?.info?.('pygmalion wakeup: waking %s (%s)', sessionId, reason ?? '(default)');
|
|
205
|
-
|
|
216
|
+
else if (kind === 'script-hook') text = buildScriptEventContext({ event, mood, topic, reason, personaName });
|
|
217
|
+
else text = buildWakeupContext({ reason, memoryHint, personaName });
|
|
218
|
+
deps.log?.info?.('pygmalion wakeup: waking %s (%s)', sessionId, reason ?? '(default)');
|
|
219
|
+
let interrupted = false;
|
|
220
|
+
// 高优先级设备生命周期事件可以打断仍在执行的 director_send(通常卡在 TTS)。
|
|
221
|
+
// 先 cancel 再入队,ReactLoopAgent 才会把该唤醒锁存在下一轮并在中断收敛后立即执行。
|
|
222
|
+
if (interruptTool && agent.status === 'running' && hasOpenToolCall(agent, interruptTool)
|
|
223
|
+
&& typeof agent.cancel === 'function') {
|
|
224
|
+
agent.cancel({ kind: 'hook', reason: `Pygmalion 高优先级事件抢占 ${interruptTool}` }, { keepInbox: true });
|
|
225
|
+
interrupted = true;
|
|
226
|
+
}
|
|
227
|
+
await agent.send({
|
|
206
228
|
id: `pygwake:${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`,
|
|
207
229
|
role: 'user',
|
|
208
230
|
content: [{ type: 'text', text }],
|
|
209
231
|
source: { kind: 'user', id: 'pygmalion-wakeup', name: 'Pygmalion 唤醒' },
|
|
210
|
-
}, 'next-turn', true);
|
|
211
|
-
|
|
212
|
-
return { ok: true, woken: true, sessionId };
|
|
213
|
-
}
|
|
232
|
+
}, 'next-turn', true);
|
|
233
|
+
|
|
234
|
+
return { ok: true, woken: true, sessionId, interrupted };
|
|
235
|
+
}
|
package/src/web-public/app.js
CHANGED
|
@@ -204,9 +204,13 @@ function openEditor(rid) {
|
|
|
204
204
|
$('#f-proactive-enabled').checked = pr.enabled !== false;
|
|
205
205
|
$('#f-maxwake').value = pr.maxWakeupsPerDay ?? 5;
|
|
206
206
|
$('#f-quiet').value = (pr.quietHours || []).join(', ');
|
|
207
|
-
$('#f-archive').value = pr.archiveIdleMinutes ?? 45;
|
|
208
|
-
$('#f-evening').value = pr.eveningCheck || '20:00';
|
|
209
|
-
const
|
|
207
|
+
$('#f-archive').value = pr.archiveIdleMinutes ?? 45;
|
|
208
|
+
$('#f-evening').value = pr.eveningCheck || '20:00';
|
|
209
|
+
const mr = pr.messageReview || {};
|
|
210
|
+
$('#f-message-review-enabled').checked = mr.enabled !== false;
|
|
211
|
+
$('#f-message-review-provider').value = mr.provider || '';
|
|
212
|
+
$('#f-message-review-model').value = mr.model || '';
|
|
213
|
+
const mc = pr.memeCollection || {};
|
|
210
214
|
$('#f-meme-enabled').checked = mc.enabled === true;
|
|
211
215
|
$('#f-meme-interval').value = mc.intervalDays ?? 7;
|
|
212
216
|
const v = mc.vision || {};
|
|
@@ -270,9 +274,14 @@ $('#role-form').addEventListener('submit', async (e) => {
|
|
|
270
274
|
enabled: $('#f-proactive-enabled').checked,
|
|
271
275
|
maxWakeupsPerDay: Number($('#f-maxwake').value) || 0,
|
|
272
276
|
quietHours: $('#f-quiet').value.split(',').map((s) => s.trim()).filter(Boolean),
|
|
273
|
-
archiveIdleMinutes: Number($('#f-archive').value) || 0,
|
|
274
|
-
eveningCheck: $('#f-evening').value.trim() || '20:00',
|
|
275
|
-
|
|
277
|
+
archiveIdleMinutes: Number($('#f-archive').value) || 0,
|
|
278
|
+
eveningCheck: $('#f-evening').value.trim() || '20:00',
|
|
279
|
+
messageReview: {
|
|
280
|
+
enabled: $('#f-message-review-enabled').checked,
|
|
281
|
+
provider: $('#f-message-review-provider').value.trim(),
|
|
282
|
+
model: $('#f-message-review-model').value.trim(),
|
|
283
|
+
},
|
|
284
|
+
memeCollection: {
|
|
276
285
|
enabled: $('#f-meme-enabled').checked,
|
|
277
286
|
intervalDays: Number($('#f-meme-interval').value) || 7,
|
|
278
287
|
vision: {
|
|
@@ -70,6 +70,8 @@
|
|
|
70
70
|
<details id="editor-proactive" class="editor-section"><summary class="section-heading"><span>03</span><div><h3>主动互动</h3><p>决定角色何时可以主动联系你。</p></div></summary>
|
|
71
71
|
<label class="switch-row"><input id="f-proactive-enabled" type="checkbox" checked><span class="switch"></span><span><b>允许主动唤醒</b><small>关闭后,角色只会回应你主动发起的对话。</small></span></label>
|
|
72
72
|
<div class="form-grid compact"><label>每日主动上限<input id="f-maxwake" type="number" min="0" max="50" value="5"></label><label>沉默归档(分钟)<input id="f-archive" type="number" min="0" value="45"></label><label>晚间问候时刻<input id="f-evening" value="20:00"></label><label>免打扰时段<input id="f-quiet" placeholder="23:00-07:00"></label></div>
|
|
73
|
+
<label class="switch-row"><input id="f-message-review-enabled" type="checkbox" checked><span class="switch"></span><span><b>发送前审查</b><small>独立检查消息分句、近期复读和 reawake 时长;审查不可用时不阻断发送。</small></span></label>
|
|
74
|
+
<details class="advanced"><summary>配置消息审查模型 <span>可选</span></summary><div class="form-grid compact"><label>Provider<input id="f-message-review-provider" placeholder="留空继承当前会话"></label><label>模型<input id="f-message-review-model" placeholder="留空继承当前会话"></label></div></details>
|
|
73
75
|
<label class="switch-row"><input id="f-meme-enabled" type="checkbox"><span class="switch"></span><span><b>周期收集表情包</b><small>导演会用搜索和视觉识别补充角色的表情库。</small></span></label>
|
|
74
76
|
<div class="form-grid compact"><label>收集周期(天)<input id="f-meme-interval" type="number" min="1" value="7"></label></div>
|
|
75
77
|
<details class="advanced"><summary>配置表情包视觉 API <span>可选</span></summary><div class="form-grid compact"><label>Provider<input id="f-meme-vision-provider" placeholder="留空自动"></label><label>视觉模型<input id="f-meme-vision-model" placeholder="deepseek-v4-flash-vision-exp"></label><label class="span-2">API 地址<input id="f-meme-vision-apiurl" placeholder="https://…"></label><label class="span-2">API Key<input id="f-meme-vision-apikey" type="password" placeholder="sk-…"></label></div></details>
|
package/src/web-server.js
CHANGED
|
@@ -278,10 +278,20 @@ export function createWebServer(deps) {
|
|
|
278
278
|
async function applyModelProactive(rid, patch) {
|
|
279
279
|
if (patch.model !== undefined) {
|
|
280
280
|
await persona.saveRoleField(rid, 'model', Object.fromEntries(Object.entries(patch.model ?? {}).filter(([, v]) => String(v ?? '').trim())));
|
|
281
|
-
}
|
|
282
|
-
if (patch.proactive !== undefined) {
|
|
283
|
-
|
|
284
|
-
|
|
281
|
+
}
|
|
282
|
+
if (patch.proactive !== undefined) {
|
|
283
|
+
const proactive = patch.proactive ?? {};
|
|
284
|
+
await persona.saveRoleField(rid, 'proactive', {
|
|
285
|
+
...persona.DEFAULT_PROACTIVE,
|
|
286
|
+
...proactive,
|
|
287
|
+
messageReview: { ...persona.DEFAULT_PROACTIVE.messageReview, ...(proactive.messageReview ?? {}) },
|
|
288
|
+
memeCollection: {
|
|
289
|
+
...persona.DEFAULT_PROACTIVE.memeCollection,
|
|
290
|
+
...(proactive.memeCollection ?? {}),
|
|
291
|
+
vision: { ...persona.DEFAULT_PROACTIVE.memeCollection.vision, ...(proactive.memeCollection?.vision ?? {}) },
|
|
292
|
+
},
|
|
293
|
+
});
|
|
294
|
+
}
|
|
285
295
|
const updated = await persona.loadRole(rid);
|
|
286
296
|
await persona.syncRoleMemory(updated);
|
|
287
297
|
if (llmProviders) {
|