pygmalion 0.1.13 → 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 +12 -8
- package/package.json +1 -1
- package/preset/pygmalion-director/agent.cordis.yml +101 -61
- package/preset/pygmalion-director/pygmalion-tools.js +22 -1
- package/src/bot-factory.js +9 -4
- package/src/devices/doc.mjs +8 -6
- package/src/devices/manager.mjs +62 -17
- package/src/heartbeat.js +6 -5
- package/src/inbound.js +4 -4
- package/src/message-review.js +276 -0
- package/src/persona.js +34 -18
- package/src/session-log.js +31 -2
- package/src/tools.js +152 -76
- package/src/voice-mimo.js +39 -9
- package/src/wakeup.js +41 -19
- 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/session-log.js
CHANGED
|
@@ -114,6 +114,26 @@ export function isRealUserMessage(ev) {
|
|
|
114
114
|
export function extractMessages(events) {
|
|
115
115
|
const userSeen = new Set();
|
|
116
116
|
const msgs = [];
|
|
117
|
+
// 新版工具调用只有在配对 tool/result 明确确认至少发送一条时才算真实角色消息。
|
|
118
|
+
// 审查退回/硬拦截同样会留下 tool/call,不能把未送达的候选写进长期原文。
|
|
119
|
+
const sentDirectorCalls = new Map();
|
|
120
|
+
for (const ev of events) {
|
|
121
|
+
if (ev?.type !== 'tool/result') continue;
|
|
122
|
+
const callId = ev.data?.message?.source?.callId;
|
|
123
|
+
const blocks = ev.data?.message?.content;
|
|
124
|
+
const rendered = (Array.isArray(blocks) ? blocks : [])
|
|
125
|
+
.filter((b) => b?.type === 'tool-result')
|
|
126
|
+
.flatMap((b) => Array.isArray(b.content) ? b.content : [])
|
|
127
|
+
.filter((b) => b?.type === 'text' && typeof b.text === 'string')
|
|
128
|
+
.map((b) => b.text).join('');
|
|
129
|
+
const success = rendered.match(/^已发送\s+(\d+)\s+条消息/);
|
|
130
|
+
const partial = rendered.match(/失败前已发送\s+(\d+)\s+条消息/);
|
|
131
|
+
const count = Number(success?.[1] ?? partial?.[1] ?? 0);
|
|
132
|
+
const timeoutMatch = rendered.match(/第\s+([\d、,,\s]+)\s+条语音合成超时/);
|
|
133
|
+
const voiceTimeouts = new Set((timeoutMatch?.[1] ?? '').split(/[、,,\s]+/)
|
|
134
|
+
.map(Number).filter((n) => Number.isInteger(n) && n > 0));
|
|
135
|
+
if (callId != null && count > 0) sentDirectorCalls.set(String(callId), { count, voiceTimeouts });
|
|
136
|
+
}
|
|
117
137
|
const push = (role, time, text) => {
|
|
118
138
|
const clean = cleanUserText(text);
|
|
119
139
|
if (!clean || isSystemText(clean)) return;
|
|
@@ -129,11 +149,20 @@ export function extractMessages(events) {
|
|
|
129
149
|
userSeen.add(key);
|
|
130
150
|
push('user', ev.time, t);
|
|
131
151
|
} else if (ev?.type === 'tool/call' && ev.data?.name === 'director_send') {
|
|
152
|
+
// 旧记录可能没有 callId,继续兼容;有 callId 的新记录必须由 tool/result 证明已发送。
|
|
153
|
+
const delivery = ev.data.callId == null
|
|
154
|
+
? { count: Number.MAX_SAFE_INTEGER, voiceTimeouts: new Set() }
|
|
155
|
+
: sentDirectorCalls.get(String(ev.data.callId));
|
|
156
|
+
const sentCount = delivery?.count ?? 0;
|
|
157
|
+
if (sentCount < 1) continue;
|
|
132
158
|
try {
|
|
133
159
|
const args = JSON.parse(ev.data.arguments ?? '{}');
|
|
134
|
-
|
|
160
|
+
const delivered = (Array.isArray(args.messages) ? args.messages : []).slice(0, sentCount);
|
|
161
|
+
for (let index = 0; index < delivered.length; index++) {
|
|
162
|
+
const m = delivered[index];
|
|
135
163
|
if (typeof m === 'string') push('character', ev.time, m);
|
|
136
|
-
else if (m && typeof m.text === 'string') push('character', ev.time,
|
|
164
|
+
else if (m && typeof m.text === 'string') push('character', ev.time,
|
|
165
|
+
m.type === 'voice' && !delivery.voiceTimeouts.has(index + 1) ? `[语音] ${m.text}` : m.text);
|
|
137
166
|
}
|
|
138
167
|
} catch { /* skip malformed */ }
|
|
139
168
|
}
|
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) {
|
|
@@ -167,24 +170,24 @@ export function buildDirectorToolDefs(resolveCtx) {
|
|
|
167
170
|
// director_send:向当前 QQ 用户发送聊天消息(导演模式的唯一发送通道)。
|
|
168
171
|
{
|
|
169
172
|
name: 'director_send',
|
|
170
|
-
description: '
|
|
171
|
-
+ 'messages
|
|
172
|
-
+ '
|
|
173
|
-
+ '
|
|
173
|
+
description: '让角色向当前 QQ 用户发送聊天消息(本模式的唯一发送通道)。QQ 用户在与角色交流,不是在与导演交流。'
|
|
174
|
+
+ 'messages 是按顺序发送的 QQ 消息气泡,每个普通文字气泡写一个自然说出的语块。闲聊回应通常是一至两条,但没有固定条数上限;'
|
|
175
|
+
+ '主动展开确有多个连续想法的话题时可以自然地发更多条。文字通常不用逗号把多个本可独立说出的分句压成长句,停顿、转折、补充或另起一个意思时直接开始下一条;'
|
|
176
|
+
+ '不要为增加数量机械拆句,也不要为减少数量塞成长句,想说完就停。不写大段文章、markdown、动作描写、心理旁白或括号情绪标签。'
|
|
177
|
+
+ '【reawake 是默认动作】发送消息时,几乎每一次都应该同时带上 reawake 参数。'
|
|
178
|
+
+ 'reawake 填一个正数,表示多少分钟后若用户没有回复,系统会在到点唤醒你重新审视情境;'
|
|
174
179
|
+ '填 "none" 或省略则表示不安排。这是维持主动联系、不让关系冷掉的机制,不安排就意味着'
|
|
175
|
-
+ '
|
|
176
|
-
+ '
|
|
177
|
-
+ '
|
|
178
|
-
+ '“中午再聊”,就把分钟数直接算到那个时刻,距离中午还有 3 个小时就填 180;如果只是平时'
|
|
179
|
-
+ '自然地把话题搁一搁,填一个适中的间隔即可。'
|
|
180
|
+
+ '这轮聊完之后你将一直静默等待用户。时长应符合真实生活,考虑用户可能离开手机、双方正在做的事、明确约定、'
|
|
181
|
+
+ '届时情境是否可能变化以及连续没有回复后自然延长的等待,不套用固定区间。reason 只记录届时重新观察的情况,'
|
|
182
|
+
+ '不预写下一条消息,也不预设醒来后一定开口。'
|
|
180
183
|
+ 'messages 为空数组时可只安排 reawake 而本次不发。'
|
|
181
184
|
+ '只允许发送拟真的、贴合角色性格的聊天文本;绝不发送思考、计划、动作描述、工具说明或任何非消息内容。'
|
|
182
|
-
+ '
|
|
185
|
+
+ '文本与语音须像真人使用 QQ 那样随情景自然选择,既不能每条都发语音,也不能长期完全不用语音。'
|
|
186
|
+
+ '语音项的 text 是原样朗读的台词;scene 写清当前事件、对象和人物动机;direction 只给一句整段成立的表演意图。'
|
|
187
|
+
+ '语音合成按台词长度设置等待时限;若超时,系统会自动把同一台词作为文字发送,并在工具结果中明确说明。'
|
|
183
188
|
+ '角色音色身份已经由管理页配置,不要在语音项重复。禁止用“前面/中段/后面”等模糊时序词、逐句声学控制、旁白或台词外心理活动。'
|
|
184
|
-
+ 'text
|
|
185
|
-
+ '
|
|
186
|
-
+ '写法参考二(雪雪已验证范例):管理页角色为中性可爱的成年男性;scene 为“哥哥不告而别且没有好好吃饭,嘴硬地训人又舍不得继续凶”;direction 为“自然表现出从生气到心软的情绪转折,在适当的地方改变语气和语调。务必注意咬字清晰”。'
|
|
187
|
-
+ '只学习二者的完整情境与克制指导,不得复制其人物、事件或措辞。'
|
|
189
|
+
+ '仅语音 text 可在必要处加入少量简短的中文圆括号语义标签,如“(轻笑)”“(压低声音)”“(停顿)”,供语音模型控制表演;'
|
|
190
|
+
+ '不把场景、心理活动或长指令塞进标签,也不用标签编排逐句变化。'
|
|
188
191
|
+ '如果你决定此刻不打扰对方,就不要调用本工具。',
|
|
189
192
|
parameters: {
|
|
190
193
|
type: 'object',
|
|
@@ -196,23 +199,22 @@ export function buildDirectorToolDefs(resolveCtx) {
|
|
|
196
199
|
{ type: 'string' },
|
|
197
200
|
{ type: 'object', additionalProperties: false, required: ['type', 'text'], properties: {
|
|
198
201
|
type: { type: 'string', enum: ['text', 'voice'] },
|
|
199
|
-
text: { type: 'string', description: '
|
|
202
|
+
text: { type: 'string', description: '普通文字的发送内容,或 voice 的朗读台词。普通文字不使用括号情绪/动作标签;仅语音台词可用少量简短圆括号语义标签控制表演,如“(轻笑)”。' },
|
|
200
203
|
scene: { type: 'string', description: '仅 voice:本条语音的完整情景、对话对象与情绪动机;不要重复管理页角色设定。' },
|
|
201
|
-
direction: { type: 'string', description: '仅 voice
|
|
204
|
+
direction: { type: 'string', description: '仅 voice:一句整体表演方向;不编排逐句变化时机,不写模糊时序词或旁白。语音表演所需的简短语义标签放在 voice 的 text 中。' },
|
|
202
205
|
} },
|
|
203
206
|
] },
|
|
204
207
|
description: '按顺序发送的消息;字符串兼容旧文本格式。voice 由角色已配置的 MiMo 音色合成并发送。空数组或省略 = 不发送。',
|
|
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
|
{
|
|
@@ -333,9 +405,9 @@ export function buildDirectorToolDefs(resolveCtx) {
|
|
|
333
405
|
const out = [];
|
|
334
406
|
// 特殊记忆:对 TA 的印象/重要事件(dsh 直接编辑);空白模板不返回。
|
|
335
407
|
try {
|
|
336
|
-
const
|
|
337
|
-
if (
|
|
338
|
-
out.push(`== 关于TA(特殊记忆)==\n${
|
|
408
|
+
const aboutUser = (await readFile(join(mem, '关于TA.md'), 'utf8')).trim();
|
|
409
|
+
if (aboutUser && aboutUser !== '(空白,等待你记录对 TA 的了解)')
|
|
410
|
+
out.push(`== 关于TA(特殊记忆)==\n${aboutUser.slice(0, 2000)}`);
|
|
339
411
|
} catch { /* 尚无特殊记忆 */ }
|
|
340
412
|
// 话题层:topics/<话题>[YYYY-MM-DD HH:MM:SS-YYYY-MM-DD HH:MM:SS]/索引.md
|
|
341
413
|
try {
|
|
@@ -380,17 +452,18 @@ export function buildDirectorToolDefs(resolveCtx) {
|
|
|
380
452
|
description: '启动你在 life/ 下写的角色生活脚本(.mjs/.js/.py/.ts,可指定文件名)。'
|
|
381
453
|
+ '脚本是“角色生活的程序化模拟器”:由你创作角色在聊天之外的经历并程序化(一天的节奏、'
|
|
382
454
|
+ '习惯、社交、心情变化、突发小事件),把经历写成可读记录(如 life/<名>.log 或工作区文件),'
|
|
383
|
-
+ '
|
|
455
|
+
+ '这样角色有自己的生活,聊天时有真实经历可谈——而不是简单的“用户很久没回就去找用户”。'
|
|
384
456
|
+ '脚本何时运行、怎么写、何时结束完全由你决定:可以长驻循环(while/setInterval),结束条件'
|
|
385
457
|
+ '写在脚本里;插件不限制运行时长/次数,只登记运行状态、把输出写进 life/.logs/,并在管理页'
|
|
386
458
|
+ '展示脚本内容与运行日志(受监管)。启动立即返回 runId/pid,脚本在后台继续跑;'
|
|
387
459
|
+ '要终止用 stop=<runId>。'
|
|
388
460
|
+ '脚本以“有事件就唤醒”为设计原则:脚本里设计的每个生活事件(心情变化、到点作息、'
|
|
389
|
-
+ '
|
|
461
|
+
+ '突发小事件、想用户的时刻)在发生时都调用 wake({ mood, topic, reason, force }) —— node '
|
|
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() 参数,否则对唤醒毫无意义。'
|
|
@@ -476,7 +549,7 @@ export function buildDirectorToolDefs(resolveCtx) {
|
|
|
476
549
|
// toy_status:查询角色可用设备状态
|
|
477
550
|
{
|
|
478
551
|
name: 'toy_status',
|
|
479
|
-
description: '
|
|
552
|
+
description: '查询当前角色已授权可用设备的状态:是否已激活(用户是否发过分享链接)、当前运行状态'
|
|
480
553
|
+ '(controller/last 参数/是否有脚本在跑)。需要操作设备前可先调用确认。',
|
|
481
554
|
parameters: {
|
|
482
555
|
type: 'object',
|
|
@@ -500,7 +573,7 @@ export function buildDirectorToolDefs(resolveCtx) {
|
|
|
500
573
|
if (!v?.ok) text = `toy_status 失败: ${v?.error ?? '?'}`;
|
|
501
574
|
else if (!v.devices?.length) text = '该角色未配置可用设备。';
|
|
502
575
|
else {
|
|
503
|
-
const lines = v.devices.map((d) => `- ${d.alias}(${d.kind}):${d.activated ? '已激活' : '
|
|
576
|
+
const lines = v.devices.map((d) => `- ${d.alias}(${d.kind}):${d.activated ? '已激活' : '未激活——需用户发分享链接'}`
|
|
504
577
|
+ (d.activated ? ` | 运行:${d.controller}${d.last ? ` 参数=${d.last.intensity !== 0 || d.last.stroke ? JSON.stringify(d.last) : ''}` : ''}${d.runId ? ` | 脚本=${d.runId}` : ''}` : ''));
|
|
505
578
|
text = ['可用设备:'].concat(lines).join('\n');
|
|
506
579
|
}
|
|
@@ -518,12 +591,13 @@ export function buildDirectorToolDefs(resolveCtx) {
|
|
|
518
591
|
// toy_control:定时/即时操控设备(工具调用模式)
|
|
519
592
|
{
|
|
520
593
|
name: 'toy_control',
|
|
521
|
-
description: '
|
|
594
|
+
description: '操控当前角色可用的玩具设备(行程+强度)。需要用户已发过一条新鲜分享链接(激活),否则会提示先请用户发。\n'
|
|
522
595
|
+ '参数:intensity 强度 0-100;stroke 行程范围(用两个边界,取值 0/33/66/100,如 "0,100"=L1~L3 全行程往复、'
|
|
523
596
|
+ '"0,66"=L1~L2 区间、"0,0"=停住;也可写区间名 "L1,L2");seconds 本次操作的时长(秒)。\n'
|
|
524
597
|
+ '计时语义:到点后设备保持当前参数继续运行,系统会提醒你计时结束,可再次调用本工具调整或 stop。'
|
|
525
|
-
+ '
|
|
526
|
-
+ '
|
|
598
|
+
+ '设备无自动停止——由你决定何时停(用户要求停时必须停);停用 stop:true。\n'
|
|
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,
|
|
@@ -552,7 +626,7 @@ export function buildDirectorToolDefs(resolveCtx) {
|
|
|
552
626
|
let text;
|
|
553
627
|
if (!v?.ok) {
|
|
554
628
|
const err = v?.error ?? '?';
|
|
555
|
-
text = `toy_control 失败: ${err}${err.includes('激活') || err.includes('分享链接') ? '(
|
|
629
|
+
text = `toy_control 失败: ${err}${err.includes('激活') || err.includes('分享链接') ? '(让用户发一条新鲜分享链接即可)' : ''}`;
|
|
556
630
|
} else {
|
|
557
631
|
const s = v.state;
|
|
558
632
|
const last = s?.last;
|
|
@@ -594,10 +668,12 @@ 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
|
-
+ '
|
|
600
|
-
+ '
|
|
671
|
+
+ '脚本与运行日志完全透明可监管:管理台「玩具操控脚本」可查看运行状态与日志(toys/.logs/)。'
|
|
672
|
+
+ '脚本启动时会清除尚未到期的 toy_control 计时提醒,避免旧控制事件与脚本撞车。'
|
|
673
|
+
+ '脚本自然结束即终止,结束时设备保持最后的参数继续运行并优先提醒你;中途停可用 stop=runId '
|
|
674
|
+
+ '或 toy_control stop。脚本运行期间不得直接改用 toy_control 接管;若要改用,必须先显式停止该脚本并确认停止。'
|
|
675
|
+
+ '每次只有一段脚本在跑,新的脚本调用会接管旧脚本。\n'
|
|
676
|
+
+ '要先激活设备(用户发分享链接);激活后参考脚本会位于 toys/玩具脚本示例.mjs。',
|
|
601
677
|
parameters: {
|
|
602
678
|
type: 'object',
|
|
603
679
|
additionalProperties: false,
|
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()) {
|
|
@@ -32,14 +46,14 @@ export function buildWakeupContext({ reason, memoryHint, personaName, now = new
|
|
|
32
46
|
parts.push('');
|
|
33
47
|
parts.push('你是被调度脚本按计划唤醒的。请作为导演,先读取工作区记忆与最近聊天,判断当下的真实情况,');
|
|
34
48
|
parts.push('包括刚才聊过什么、用户是否正在聊天、情境是否已经变化,然后再决定角色此刻是否开口以及');
|
|
35
|
-
parts.push('
|
|
49
|
+
parts.push('要说什么。角色可以顺势参与对话,也可以选择保持沉默。');
|
|
36
50
|
return parts.join('\n');
|
|
37
51
|
}
|
|
38
52
|
|
|
39
53
|
/** 归档任务情境:用户长时间未发言时,把原始记录按话题切片归档为双份记忆并建索引。 */
|
|
40
54
|
export function buildArchiveContext({ date, workspace, now = new Date() }) {
|
|
41
55
|
const parts = [
|
|
42
|
-
'[归档任务]
|
|
56
|
+
'[归档任务] 角色与用户的对话已沉默一段时间(用户 45 分钟以上未发新消息),现在整理记忆。',
|
|
43
57
|
'时间:' + nowText(now),
|
|
44
58
|
'工作区:' + (workspace ?? ''),
|
|
45
59
|
];
|
|
@@ -60,7 +74,7 @@ export function buildArchiveContext({ date, workspace, now = new Date() }) {
|
|
|
60
74
|
}
|
|
61
75
|
|
|
62
76
|
/**
|
|
63
|
-
*
|
|
77
|
+
* “脚本事件”情境:角色的生活脚本报来一个生活事件(想用户、心情变化、突发小事件),
|
|
64
78
|
* 唤醒导演判断此刻是否由角色开口。脚本侧一行 wake() 即可触发。
|
|
65
79
|
*/
|
|
66
80
|
export function buildScriptEventContext({ event, mood, topic, reason, personaName, now = new Date() }) {
|
|
@@ -77,7 +91,7 @@ export function buildScriptEventContext({ event, mood, topic, reason, personaNam
|
|
|
77
91
|
parts.push('');
|
|
78
92
|
parts.push('这是脚本按你设计的事件唤醒你(“有事件就唤醒”:脚本遇到事件就报来,不主动决定开口)。');
|
|
79
93
|
parts.push('请作为导演,先读取脚本写下的生活记录(如 life/<名>.log 或工作区记录文件)与最近聊天,');
|
|
80
|
-
parts.push('
|
|
94
|
+
parts.push('自行判断此刻是否由角色开口:想用户了、想分享刚发生的事,就通过 director_send 发送一条');
|
|
81
95
|
parts.push('自然的消息;也可以选择沉默(如刚聊过、用户正忙、当下开口不合适)。脚本只负责报事件,');
|
|
82
96
|
parts.push('开口与否、如何开口,由你决定。像真实生活那样自然地行动,');
|
|
83
97
|
parts.push('不要念设定,不要提及“导演 / 脚本 / 系统”。');
|
|
@@ -97,17 +111,17 @@ export function buildLifeWindowContext({ reason, personaName, hasLifeScript, now
|
|
|
97
111
|
parts.push('');
|
|
98
112
|
if (hasLifeScript) {
|
|
99
113
|
parts.push('你的生活脚本在跑(life/ 下已有脚本,可读 life/.manifest.json 查看清单与最近的运行状态)。');
|
|
100
|
-
parts.push('
|
|
114
|
+
parts.push('现在你需要自行判断:如果角色此刻会主动联系用户,就用 life_run 查看或调整脚本,根据脚本记录的生活');
|
|
101
115
|
parts.push('决定是否通过 director_send 开口;如果刚聊过、此刻不打扰更合适,也可以选择这轮保持静默。');
|
|
102
116
|
} else {
|
|
103
117
|
parts.push('现在是“非零性检查”:当前没有任何生活脚本在运行。这个项目不是聊天机器人——');
|
|
104
|
-
parts.push('
|
|
118
|
+
parts.push('是要让角色有真实的生活:角色在与用户聊天之外,还应该有自己的生活(一天怎么过、习惯与小事、');
|
|
105
119
|
parts.push('心情变化、突发的小事件)。你是导演,职责是创作这些经历、把它们程序化为脚本,');
|
|
106
120
|
parts.push('让脚本模拟并记录角色的生活(如写到 life/<名>.log 或工作区文件),这样聊天时角色有真实经历可谈。');
|
|
107
121
|
parts.push('现在做两件事:');
|
|
108
122
|
parts.push('1. 新建一个你的生活脚本(新文件,勿覆盖 life/ 下已有文件)——写角色真实的生活细节,');
|
|
109
|
-
parts.push('
|
|
110
|
-
parts.push('
|
|
123
|
+
parts.push(' 不是简单的“用户很久没回就去找用户”;以“有事件就唤醒”为原则:脚本里设计的每个');
|
|
124
|
+
parts.push(' 事件(心情变化、到点作息、突发小事件、想用户的时刻)发生时都调用 wake() 报给你,');
|
|
111
125
|
parts.push(' 由你判断是否开口——没有被唤醒的事件就失去了意义;');
|
|
112
126
|
parts.push('2. 用 life_run 启动它(立即返回,脚本在后台继续跑,由脚本自己决定何时结束;');
|
|
113
127
|
parts.push(' 插件只监管展示、不限制运行时长/次数)。');
|
|
@@ -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
|
+
}
|