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/devices/manager.mjs
CHANGED
|
@@ -111,12 +111,13 @@ export function createDeviceManager(deps) {
|
|
|
111
111
|
const persona = deps.persona;
|
|
112
112
|
const log = deps.log;
|
|
113
113
|
const baseUrl = deps.baseUrl || DEFAULT_BASE;
|
|
114
|
+
const drivers = deps.drivers || DRIVERS;
|
|
114
115
|
|
|
115
116
|
/** roleId → { deviceId, alias, token, session }(内存激活态,token 不落盘) */
|
|
116
117
|
const activations = new Map();
|
|
117
118
|
/** roleId → DeviceRuntime */
|
|
118
119
|
const runtimes = new Map();
|
|
119
|
-
/** roleId → wake 闭包(bot-factory 注入):async (contextText) => wakeupSession(...) */
|
|
120
|
+
/** roleId → wake 闭包(bot-factory 注入):async (contextText, { priority }) => wakeupSession(...) */
|
|
120
121
|
const wakes = new Map();
|
|
121
122
|
/** runId → script run */
|
|
122
123
|
const scriptRuns = new Map();
|
|
@@ -165,6 +166,7 @@ export function createDeviceManager(deps) {
|
|
|
165
166
|
controller: 'idle', // idle | tool | script
|
|
166
167
|
last: { intensity: 0, stroke: null },
|
|
167
168
|
phaseTimer: null,
|
|
169
|
+
phaseGeneration: 0,
|
|
168
170
|
script: null,
|
|
169
171
|
lastRemindAt: 0,
|
|
170
172
|
};
|
|
@@ -174,6 +176,7 @@ export function createDeviceManager(deps) {
|
|
|
174
176
|
}
|
|
175
177
|
|
|
176
178
|
function clearPhase(rt) {
|
|
179
|
+
rt.phaseGeneration++;
|
|
177
180
|
if (rt.phaseTimer) { clearTimeout(rt.phaseTimer); rt.phaseTimer = null; }
|
|
178
181
|
}
|
|
179
182
|
function killScript(rt) {
|
|
@@ -186,6 +189,27 @@ export function createDeviceManager(deps) {
|
|
|
186
189
|
rt.script = null;
|
|
187
190
|
if (ws) persistToysRunning(ws);
|
|
188
191
|
}
|
|
192
|
+
async function waitForChildExit(child, timeoutMs) {
|
|
193
|
+
if (!child || child.exitCode !== null || child.signalCode != null) return true;
|
|
194
|
+
return await new Promise((resolveDone) => {
|
|
195
|
+
let settled = false;
|
|
196
|
+
const done = (value) => {
|
|
197
|
+
if (settled) return;
|
|
198
|
+
settled = true;
|
|
199
|
+
clearTimeout(timer);
|
|
200
|
+
child.off('close', onClose);
|
|
201
|
+
child.off('error', onError);
|
|
202
|
+
resolveDone(value);
|
|
203
|
+
};
|
|
204
|
+
const onClose = () => done(true);
|
|
205
|
+
const onError = () => done(true);
|
|
206
|
+
const timer = setTimeout(() => done(false), timeoutMs);
|
|
207
|
+
timer.unref?.();
|
|
208
|
+
child.once('close', onClose);
|
|
209
|
+
child.once('error', onError);
|
|
210
|
+
if (child.exitCode !== null || child.signalCode != null) done(true);
|
|
211
|
+
});
|
|
212
|
+
}
|
|
189
213
|
async function stopConn(rt) {
|
|
190
214
|
const conn = rt.conn;
|
|
191
215
|
if (conn) {
|
|
@@ -201,7 +225,7 @@ export function createDeviceManager(deps) {
|
|
|
201
225
|
if (rt.conn) return null;
|
|
202
226
|
const act = rt.activation;
|
|
203
227
|
if (!act) return { error: '设备未激活', code: 'not-activated' };
|
|
204
|
-
const drv =
|
|
228
|
+
const drv = drivers[act.kind];
|
|
205
229
|
if (!drv) return { error: `未知设备类型 ${act.kind}`, code: 'no-driver' };
|
|
206
230
|
const conn = new drv.Conn(act.session, { log });
|
|
207
231
|
try {
|
|
@@ -231,18 +255,20 @@ export function createDeviceManager(deps) {
|
|
|
231
255
|
}
|
|
232
256
|
|
|
233
257
|
/** 提醒 dsh(10s 合并同类)。contextText 已是 [设备事件] 文本。 */
|
|
234
|
-
async function notify(rt, text) {
|
|
258
|
+
async function notify(rt, text, { priority = false } = {}) {
|
|
235
259
|
const wake = wakes.get(rt.roleId);
|
|
236
260
|
if (typeof wake !== 'function') return { ok: false, error: 'no-wake' };
|
|
237
261
|
const now = Date.now();
|
|
238
|
-
if (now - rt.lastRemindAt < REMIND_COALESCE_MS) return { ok: false, skipped: 'coalesced' };
|
|
262
|
+
if (!priority && now - rt.lastRemindAt < REMIND_COALESCE_MS) return { ok: false, skipped: 'coalesced' };
|
|
239
263
|
rt.lastRemindAt = now;
|
|
240
|
-
try { await wake(text); return { ok: true }; }
|
|
264
|
+
try { await wake(text, { priority }); return { ok: true }; }
|
|
241
265
|
catch (e) { warn('device notify role=%s fail: %s', rt.roleId, e?.message ?? e); return { ok: false, error: String(e) }; }
|
|
242
266
|
}
|
|
243
267
|
|
|
244
268
|
/** 结束一段(工具计时到点 / 脚本结束):保持当前参数,提醒 dsh。 */
|
|
245
|
-
async function finishPhase(rt, { kind, detail }) {
|
|
269
|
+
async function finishPhase(rt, { kind, detail, phaseGeneration }) {
|
|
270
|
+
// 被后续脚本/工具清除的旧计时,即使回调已经进入任务队列也不能再唤醒导演。
|
|
271
|
+
if (kind === 'tool' && phaseGeneration !== rt.phaseGeneration) return;
|
|
246
272
|
rt.phaseTimer = null;
|
|
247
273
|
rt.controller = 'idle'; // 设备仍在跑(conn 持续刷新),dsh 决定再调或停
|
|
248
274
|
const lastText = rt.last.stroke
|
|
@@ -253,7 +279,7 @@ export function createDeviceManager(deps) {
|
|
|
253
279
|
const text = kind === 'script'
|
|
254
280
|
? `[设备事件] 你的操控脚本「${detail}」已结束,当前设备保持最后参数(${lastText})继续运行。若需要可再 toy_run_script 或 toy_control;要停用 toy_control 停。`
|
|
255
281
|
: `[设备事件] 本次 toy_control 计时结束,设备保持当前参数(${lastText})继续运行。可再次调用 toy_control 调整或停止。`;
|
|
256
|
-
await notify(rt, text);
|
|
282
|
+
await notify(rt, text, { priority: kind === 'script' });
|
|
257
283
|
}
|
|
258
284
|
|
|
259
285
|
// ---------------- 对外 API ----------------
|
|
@@ -264,7 +290,7 @@ export function createDeviceManager(deps) {
|
|
|
264
290
|
/** 文本里找设备分享链接。@returns { token, raw, kind } | null */
|
|
265
291
|
detectLink(text) {
|
|
266
292
|
const s = String(text ?? '');
|
|
267
|
-
for (const drv of Object.values(
|
|
293
|
+
for (const drv of Object.values(drivers)) {
|
|
268
294
|
const hit = drv.parseLink(s);
|
|
269
295
|
if (hit) return hit;
|
|
270
296
|
}
|
|
@@ -284,7 +310,7 @@ export function createDeviceManager(deps) {
|
|
|
284
310
|
// 匹配该角色授权中的 monsterparty 设备(链接可能来自任一授权设备,单台场景直接命中)
|
|
285
311
|
const dev = await authorizedDevice(role, 'monsterparty', null);
|
|
286
312
|
if (!dev) return { ok: false, error: '该角色未配置可用设备(请在管理台「我的设备」登记并为角色勾选)', code: 'no-device' };
|
|
287
|
-
const res = await
|
|
313
|
+
const res = await drivers.monsterparty.resolveSession(token);
|
|
288
314
|
if (!res.ok) return { ok: false, error: res.error, code: 'invalid' };
|
|
289
315
|
// 若已激活/已连旧会话 → 断开旧 conn(等新 token 用于下次 apply)
|
|
290
316
|
const old = runtimes.get(roleId);
|
|
@@ -332,13 +358,24 @@ export function createDeviceManager(deps) {
|
|
|
332
358
|
|
|
333
359
|
// stop:停当前(脚本自身 stop 不杀自己,只停设备;dsh 工具 stop 清计时+杀脚本)
|
|
334
360
|
if (params.stop === true) {
|
|
361
|
+
const stoppedScript = !fromScript ? rt.script : null;
|
|
335
362
|
if (!fromScript) { clearPhase(rt); killScript(rt); }
|
|
336
363
|
await stopConn(rt);
|
|
337
364
|
rt.last = { intensity: 0, stroke: null };
|
|
338
365
|
if (!fromScript) rt.controller = 'idle';
|
|
366
|
+
if (stoppedScript) {
|
|
367
|
+
await notify(rt, `[设备事件] 玩具操控脚本「${basename(stoppedScript.script)}」已被 toy_control stop 终止,设备也已停止。`,
|
|
368
|
+
{ priority: true });
|
|
369
|
+
}
|
|
339
370
|
return { ok: true, state: rtState(rt) };
|
|
340
371
|
}
|
|
341
372
|
|
|
373
|
+
// 玩具脚本拥有排他的控制权。普通工具调用不得暗中杀掉脚本;导演必须先显式终止脚本。
|
|
374
|
+
if (!fromScript && rt.script) {
|
|
375
|
+
return { ok: false, code: 'script-active',
|
|
376
|
+
error: `玩具脚本「${basename(rt.script.script)}」正在运行(runId=${rt.script.runId});请先用 toy_run_script stop=${rt.script.runId} 终止脚本,再调用 toy_control。` };
|
|
377
|
+
}
|
|
378
|
+
|
|
342
379
|
// 激活检查:必须是这台授权设备
|
|
343
380
|
const act = activations.get(roleId);
|
|
344
381
|
if (!act || act.deviceId !== dev.id) {
|
|
@@ -349,12 +386,12 @@ export function createDeviceManager(deps) {
|
|
|
349
386
|
rt.activation = act;
|
|
350
387
|
rt.deviceId = dev.id;
|
|
351
388
|
|
|
352
|
-
//
|
|
353
|
-
if (!fromScript &&
|
|
389
|
+
// 普通工具的新计时可替换旧计时;脚本自身调用始终保持 script 控制者。
|
|
390
|
+
if (!fromScript && rt.phaseTimer) clearPhase(rt);
|
|
354
391
|
const err = await ensureConn(rt);
|
|
355
392
|
if (err) { rt.activation = null; activations.delete(roleId); return { ok: false, ...err }; }
|
|
356
393
|
|
|
357
|
-
const cap =
|
|
394
|
+
const cap = drivers.monsterparty.capability;
|
|
358
395
|
// 参数归一
|
|
359
396
|
if (params.intensity !== undefined) {
|
|
360
397
|
const v = Math.max(cap.intensity.min, Math.min(cap.intensity.max, Math.round(Number(params.intensity))));
|
|
@@ -376,7 +413,8 @@ export function createDeviceManager(deps) {
|
|
|
376
413
|
clearPhase(rt);
|
|
377
414
|
const ms = Math.round(Number(params.seconds) * 1000);
|
|
378
415
|
rt.controller = 'tool';
|
|
379
|
-
|
|
416
|
+
const phaseGeneration = rt.phaseGeneration;
|
|
417
|
+
rt.phaseTimer = setTimeout(() => { void finishPhase(rt, { kind: 'tool', phaseGeneration }); }, ms);
|
|
380
418
|
rt.phaseTimer.unref?.();
|
|
381
419
|
} else {
|
|
382
420
|
rt.controller = 'tool';
|
|
@@ -449,7 +487,7 @@ export function createDeviceManager(deps) {
|
|
|
449
487
|
scriptRuns.delete(runId);
|
|
450
488
|
persistToysRunning(workspace);
|
|
451
489
|
if (fd != null) { try { closeSync(fd); } catch { /* ignore */ } }
|
|
452
|
-
if (stillCurrent) void notify(rt, `[脚本结束] 玩具脚本「${basename(full)}」启动失败:${e.message}\n日志目录:toys/.logs
|
|
490
|
+
if (stillCurrent) void notify(rt, `[脚本结束] 玩具脚本「${basename(full)}」启动失败:${e.message}\n日志目录:toys/.logs/`, { priority: true });
|
|
453
491
|
});
|
|
454
492
|
child.on('close', (code) => {
|
|
455
493
|
if (fd != null) { try { closeSync(fd); } catch { /* ignore */ } }
|
|
@@ -457,7 +495,7 @@ export function createDeviceManager(deps) {
|
|
|
457
495
|
if (rt.script?.runId === runId) { rt.script = null; rt.controller = 'idle'; }
|
|
458
496
|
scriptRuns.delete(runId);
|
|
459
497
|
persistToysRunning(workspace);
|
|
460
|
-
if (stillCurrent) {
|
|
498
|
+
if (stillCurrent && run.stopping !== true) {
|
|
461
499
|
const label = basename(full);
|
|
462
500
|
void finishPhase(rt, { kind: 'script', detail: label, exitCode: code });
|
|
463
501
|
}
|
|
@@ -469,7 +507,14 @@ export function createDeviceManager(deps) {
|
|
|
469
507
|
async stopScript(runId) {
|
|
470
508
|
const run = scriptRuns.get(String(runId));
|
|
471
509
|
if (!run) return { ok: false, error: `没有运行中的脚本 runId=${runId}` };
|
|
472
|
-
|
|
510
|
+
run.stopping = true;
|
|
511
|
+
if (run.child) {
|
|
512
|
+
try { run.child.kill('SIGTERM'); } catch { /* ignore */ }
|
|
513
|
+
if (!await waitForChildExit(run.child, 1_000)) {
|
|
514
|
+
try { run.child.kill('SIGKILL'); } catch { /* ignore */ }
|
|
515
|
+
await waitForChildExit(run.child, 1_000);
|
|
516
|
+
}
|
|
517
|
+
}
|
|
473
518
|
scriptRuns.delete(run.runId);
|
|
474
519
|
persistToysRunning(run.workspace);
|
|
475
520
|
const rt = runtimes.get(run.roleId);
|
|
@@ -483,7 +528,7 @@ export function createDeviceManager(deps) {
|
|
|
483
528
|
? `强度 ${last.intensity}`
|
|
484
529
|
: '已停';
|
|
485
530
|
void notify(rt, `[设备事件] 玩具操控脚本「${basename(run.script)}」已停止,设备保持最后一刻参数(${lastText})继续运行、不中断。`
|
|
486
|
-
+ '如需延续可再 toy_run_script 续一段,或 toy_control 调整;真正要停设备用 toy_control stop。');
|
|
531
|
+
+ '如需延续可再 toy_run_script 续一段,或 toy_control 调整;真正要停设备用 toy_control stop。', { priority: true });
|
|
487
532
|
}
|
|
488
533
|
return { ok: true, stopped: run.runId };
|
|
489
534
|
},
|
package/src/heartbeat.js
CHANGED
|
@@ -272,11 +272,12 @@ export function createHeartbeatScheduler(deps) {
|
|
|
272
272
|
// 免打扰时段:rewake 到期也不立即唤醒,留在队列等安静时段结束后的下一 tick 再发。
|
|
273
273
|
if (inQuietHours(role.proactive?.quietHours || [], now)) continue;
|
|
274
274
|
try {
|
|
275
|
-
await wakeupSession(wakeBaseFor(pipeline), {
|
|
276
|
-
target: { kind: 'c2c', userId: openid },
|
|
277
|
-
reason: '
|
|
278
|
-
memoryHint:
|
|
279
|
-
|
|
275
|
+
await wakeupSession(wakeBaseFor(pipeline), {
|
|
276
|
+
target: { kind: 'c2c', userId: openid },
|
|
277
|
+
reason: 'reawake 到期,重新审视当前情境',
|
|
278
|
+
memoryHint: `此前留下的观察线索:${r.reason}。用户在这段时间没有发消息。`
|
|
279
|
+
+ '这只是供此刻重新判断的线索,不是待执行的发言计划,也不表示现在必须开口。',
|
|
280
|
+
});
|
|
280
281
|
log?.info?.('pygmalion heartbeat: rewake due for role %s', role.roleId);
|
|
281
282
|
} catch (e) { log?.warn?.('pygmalion rewake %s failed: %o', role.roleId, e); }
|
|
282
283
|
state.rewake = state.rewake.filter((x) => x !== r);
|
package/src/inbound.js
CHANGED
|
@@ -513,8 +513,8 @@ export class InboundPipeline {
|
|
|
513
513
|
extras.unshift(running.length
|
|
514
514
|
? `[生活脚本] 有脚本在跑(${running.map((r) => r.scriptName).join('、')}),非零已满足。`
|
|
515
515
|
: scripts.length
|
|
516
|
-
? `[生活脚本] life/ 下有脚本(${scripts.join('、')}
|
|
517
|
-
: '[生活脚本] life/
|
|
516
|
+
? `[生活脚本] life/ 下有脚本(${scripts.join('、')})但当前都没有在跑——想保留主动关心用户的可能,可用 life_run 重启一个。`
|
|
517
|
+
: '[生活脚本] life/ 当前没有任何脚本在跑(不满足“非零”)。若想保留主动关心用户的可能,可新建一个你的脚本(新文件,勿覆盖已有文件)并用 life_run 运行。');
|
|
518
518
|
}
|
|
519
519
|
} catch (e) { this.deps.log.warn('life script hint failed: %o', e); }
|
|
520
520
|
}
|
|
@@ -523,7 +523,7 @@ export class InboundPipeline {
|
|
|
523
523
|
if (this.deps.roleId && this.deps.persona?.roleWorkspace) {
|
|
524
524
|
try {
|
|
525
525
|
if (await isRoleDirectorSession(this.deps.roleId, sessionId))
|
|
526
|
-
extras.unshift('[身份提醒]
|
|
526
|
+
extras.unshift('[身份提醒] 这条 QQ 消息发给角色,不是发给导演;你只在幕后决定角色如何回应,角色发言只走 director_send。');
|
|
527
527
|
} catch (e) { this.deps.log.warn('identity hint failed: %o', e); }
|
|
528
528
|
}
|
|
529
529
|
// 设备分享链接激活(仅 c2c 拥有者会话):识别 MonsterParty 链接 → 解析 → 激活该角色设备;
|
|
@@ -814,4 +814,4 @@ export function botIdOfSession(sessionId) {
|
|
|
814
814
|
const parts = String(sessionId ?? '').split('#')[0].split(':');
|
|
815
815
|
return parts[1] === 'v2' && parts.length >= 3 ? parts[2] : undefined;
|
|
816
816
|
}
|
|
817
|
-
//# sourceMappingURL=inbound.js.map
|
|
817
|
+
//# sourceMappingURL=inbound.js.map
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* director_send 发送前审查。
|
|
3
|
+
*
|
|
4
|
+
* 两层边界:
|
|
5
|
+
* 1. 确定性校验只拒绝不可能属于角色消息的控制文本、系统标记、普通文字舞台标签、
|
|
6
|
+
* 空白项与同批重复;不按消息条数或逗号数量硬裁决。
|
|
7
|
+
* 2. 可选 LLM 审查独立判断 QQ 分句、近期复读、人物一致性与 reawake 时长是否自然。
|
|
8
|
+
* 审查器只给通过/退回意见,不代写角色消息。
|
|
9
|
+
*/
|
|
10
|
+
import { randomUUID } from 'node:crypto';
|
|
11
|
+
|
|
12
|
+
const QQ_OPENID_RE = /^[0-9A-F]{32}$/i;
|
|
13
|
+
const SYSTEM_MARKER_RE = /\[(?:时间线|唤醒事件|脚本事件|生活窗口|脚本审阅|归档任务|设备事件|HTTP 推送记录)\]/;
|
|
14
|
+
const CONTROL_WORD_RE = /\b(?:reawake|director_send)\b/i;
|
|
15
|
+
const TEXT_STAGE_RE = /^\s*[((][^()()\r\n]{1,30}[))]/;
|
|
16
|
+
|
|
17
|
+
function textOfBlocks(content) {
|
|
18
|
+
return (Array.isArray(content) ? content : [])
|
|
19
|
+
.filter((block) => block?.type === 'text' && typeof block.text === 'string')
|
|
20
|
+
.map((block) => block.text)
|
|
21
|
+
.join('')
|
|
22
|
+
.trim();
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function messageTexts(raw) {
|
|
26
|
+
const out = [];
|
|
27
|
+
for (const item of Array.isArray(raw) ? raw : []) {
|
|
28
|
+
const text = typeof item === 'string' ? item.trim() : String(item?.text ?? '').trim();
|
|
29
|
+
if (text) out.push(text);
|
|
30
|
+
}
|
|
31
|
+
return out;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** 把 director_send 的兼容输入规范化为内部消息对象。 */
|
|
35
|
+
export function normalizeDirectorMessages(raw) {
|
|
36
|
+
return (Array.isArray(raw) ? raw : []).map((item) => typeof item === 'string'
|
|
37
|
+
? { type: 'text', text: item.trim() }
|
|
38
|
+
: {
|
|
39
|
+
type: item?.type === 'voice' ? 'voice' : 'text',
|
|
40
|
+
text: String(item?.text ?? '').trim(),
|
|
41
|
+
scene: String(item?.scene ?? '').trim(),
|
|
42
|
+
direction: String(item?.direction ?? '').trim(),
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function duplicateKey(text) {
|
|
47
|
+
return String(text).toLowerCase().replace(/\s+/g, '').replace(/[。!?!?…~~]+$/g, '');
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* 不依赖模型的硬校验。空 messages 合法(只安排 reawake);数组中的空白项不合法。
|
|
52
|
+
* 返回面向导演的具体退回理由。
|
|
53
|
+
*/
|
|
54
|
+
export function validateDirectorMessages(raw, messages = normalizeDirectorMessages(raw)) {
|
|
55
|
+
const issues = [];
|
|
56
|
+
const list = Array.isArray(raw) ? raw : [];
|
|
57
|
+
if (list.some((item) => (typeof item === 'string' ? item : item?.text) == null
|
|
58
|
+
|| String(typeof item === 'string' ? item : item?.text).trim().length === 0)) {
|
|
59
|
+
issues.push('messages 中含空白消息;空数组可以表示本次不发送,但数组中的每一项都必须有内容');
|
|
60
|
+
}
|
|
61
|
+
const seen = new Set();
|
|
62
|
+
for (let i = 0; i < messages.length; i++) {
|
|
63
|
+
const msg = messages[i];
|
|
64
|
+
const label = `第 ${i + 1} 条消息`;
|
|
65
|
+
if (CONTROL_WORD_RE.test(msg.text)) issues.push(`${label}包含内部控制词`);
|
|
66
|
+
if (SYSTEM_MARKER_RE.test(msg.text)) issues.push(`${label}包含系统情境标记`);
|
|
67
|
+
if (msg.type === 'text' && TEXT_STAGE_RE.test(msg.text)) issues.push(`${label}以括号舞台/情绪标签开头;此类标签仅可用于语音台词`);
|
|
68
|
+
const key = duplicateKey(msg.text);
|
|
69
|
+
if (key && seen.has(key)) issues.push(`${label}与本次调用中的前一条消息重复`);
|
|
70
|
+
if (key) seen.add(key);
|
|
71
|
+
}
|
|
72
|
+
return [...new Set(issues)];
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function sentCountFromRendered(text) {
|
|
76
|
+
const success = String(text).match(/^已发送\s+(\d+)\s+条消息/);
|
|
77
|
+
const partial = String(text).match(/失败前已发送\s+(\d+)\s+条消息/);
|
|
78
|
+
return Number(success?.[1] ?? partial?.[1] ?? 0);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function parseDirectorCall(block, sentCounts) {
|
|
82
|
+
if (block?.type !== 'tool-call' || block.name !== 'director_send') return [];
|
|
83
|
+
// 新会话中的工具调用都有 id:只有配对结果明确显示至少发送一条时才进入真实 QQ 历史。
|
|
84
|
+
// 无 id 是旧日志/测试兼容形态,沿用原来的调用即发送假设。
|
|
85
|
+
const sentCount = block.id == null ? Number.MAX_SAFE_INTEGER : (sentCounts.get(String(block.id)) ?? 0);
|
|
86
|
+
if (sentCount < 1) return [];
|
|
87
|
+
try {
|
|
88
|
+
const args = JSON.parse(block.arguments ?? '{}');
|
|
89
|
+
return messageTexts(args.messages).slice(0, sentCount).map((text) => ({ role: 'character', text }));
|
|
90
|
+
} catch {
|
|
91
|
+
return [];
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* 从当前 agent 的派生消息中提取最近真实 QQ 对话。
|
|
97
|
+
* 工具执行时最后一条 assistant message 含本次候选 tool-call,必须排除,避免候选与自己比较。
|
|
98
|
+
*/
|
|
99
|
+
export function recentQQConversation(agent, limit = 30) {
|
|
100
|
+
let derived = [];
|
|
101
|
+
try { derived = agent?.session?.deriveMessages?.() ?? []; } catch { return []; }
|
|
102
|
+
const history = derived.length > 0 && derived.at(-1)?.role === 'assistant' ? derived.slice(0, -1) : derived;
|
|
103
|
+
const sentCounts = new Map();
|
|
104
|
+
for (const message of history) {
|
|
105
|
+
if (message?.role !== 'user') continue;
|
|
106
|
+
for (const block of Array.isArray(message.content) ? message.content : []) {
|
|
107
|
+
if (block?.type !== 'tool-result' || block.toolCallId == null) continue;
|
|
108
|
+
const rendered = textOfBlocks(block.content);
|
|
109
|
+
const count = sentCountFromRendered(rendered);
|
|
110
|
+
if (count > 0) sentCounts.set(String(block.toolCallId), count);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
const out = [];
|
|
114
|
+
for (const message of history) {
|
|
115
|
+
if (message?.role === 'user' && message?.source?.kind === 'user'
|
|
116
|
+
&& typeof message.source.id === 'string' && QQ_OPENID_RE.test(message.source.id)) {
|
|
117
|
+
const text = textOfBlocks(message.content);
|
|
118
|
+
if (text) out.push({ role: 'user', text: text.slice(0, 1200) });
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
if (message?.role !== 'assistant') continue;
|
|
122
|
+
for (const block of Array.isArray(message.content) ? message.content : []) out.push(...parseDirectorCall(block, sentCounts));
|
|
123
|
+
}
|
|
124
|
+
return out.slice(-Math.max(1, limit));
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** 当前轮的模型侧情境(QQ 用户消息或唤醒注入),供审查器理解为什么会调用发送工具。 */
|
|
128
|
+
export function currentTurnContext(agent) {
|
|
129
|
+
let derived = [];
|
|
130
|
+
try { derived = agent?.session?.deriveMessages?.() ?? []; } catch { return ''; }
|
|
131
|
+
for (let i = derived.length - 1; i >= 0; i--) {
|
|
132
|
+
if (derived[i]?.role !== 'user') continue;
|
|
133
|
+
const text = textOfBlocks(derived[i].content);
|
|
134
|
+
if (text) return text.slice(0, 2400);
|
|
135
|
+
}
|
|
136
|
+
return '';
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** 优先用审查覆盖配置,否则继承当前会话最后一次实际请求的 route,再退到 agent options。 */
|
|
140
|
+
export function resolveReviewRoute(reviewConfig, agent) {
|
|
141
|
+
const latest = agent?.session?.requestHeader?.()?.config;
|
|
142
|
+
const fallback = latest?.provider && latest?.model
|
|
143
|
+
? latest
|
|
144
|
+
: (agent?.options?.provider && agent?.options?.model ? agent.options : undefined);
|
|
145
|
+
const provider = String(reviewConfig?.provider ?? '').trim() || fallback?.provider;
|
|
146
|
+
const model = String(reviewConfig?.model ?? '').trim() || fallback?.model;
|
|
147
|
+
return provider && model ? { provider, model } : undefined;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function personaForReview(role) {
|
|
151
|
+
const p = role?.persona ?? {};
|
|
152
|
+
return {
|
|
153
|
+
name: String(p.name ?? '').slice(0, 100),
|
|
154
|
+
age: String(p.age ?? '').slice(0, 100),
|
|
155
|
+
personality: String(p.personality ?? '').slice(0, 1200),
|
|
156
|
+
backstory: String(p.backstory ?? '').slice(0, 1600),
|
|
157
|
+
speakingStyle: String(p.speakingStyle ?? '').slice(0, 1200),
|
|
158
|
+
relationship: String(p.relationship ?? '').slice(0, 1200),
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export function buildReviewSystemPrompt() {
|
|
163
|
+
return [
|
|
164
|
+
'你是 Pygmalion 的 QQ 消息发送前审查器。你只判断候选输出是否自然,不扮演角色、不改写消息。',
|
|
165
|
+
'角色不是 AI agent、AI 助手或围绕用户任务运转的服务者。候选行动和发言必须由人物设定、过往经历、当前处境与关系状态共同支持,',
|
|
166
|
+
'不得呈现通用 AI 助手的默认目标、工作方式、话术结构或交互习惯。',
|
|
167
|
+
'人物设定中的说话风格说明、Q&A、示范对话和其他表达指导,是判断候选措辞、语气与表达方式的直接依据;明显偏离时应退回。',
|
|
168
|
+
'与明确人物设定冲突,或把导演、AI agent、AI 助手的特征带入角色的候选属于 OOC,必须退回。',
|
|
169
|
+
'近期聊天只用于判断事实、事件、承诺、关系变化和延续影响。不得把近期或更早的消息文本当作文风依据,也不得因历史中反复出现某种写法就认可它。',
|
|
170
|
+
'消息数量没有固定上限。闲聊回应常见一至两条;主动展开确有多个连续想法的话题时,三至五条或更多也可以。',
|
|
171
|
+
'每个气泡应是人在聊天框中自然敲出的一个语块。书面长句用逗号连接多个本可独立说出的分句通常不自然;',
|
|
172
|
+
'但不能为了增加数量机械拆句,也不能因条数多就判错。判断每个气泡是否有真实的分句、停顿、补充或推进理由。',
|
|
173
|
+
'重点识别:近期事实或问题复读;用户已经回答后仍追问;通用 AI 助手式表达;偏离人物设定中的语言指导;',
|
|
174
|
+
'照搬历史消息的表达习惯;为了展示人设而额外制造态度或语言特征;控制信息泄漏。',
|
|
175
|
+
'不预设角色对用户的态度方向,也不以亲密程度、配合程度或情绪性质本身作为通过或退回的依据。',
|
|
176
|
+
'reawake 必须让关系仍有继续的可能,但时长要符合现实:考虑用户离开手机、正在做的事、明确约定、',
|
|
177
|
+
'届时情境是否可能变化以及连续未回复后的自然等待。reason 是届时重新观察的线索,不能是预写好的下一条消息。',
|
|
178
|
+
'只输出一个 JSON 对象,不加 markdown 或解释:',
|
|
179
|
+
'{"messages":{"pass":true,"reasons":[]},"reawake":{"reasonable":true,"reason":""}}',
|
|
180
|
+
].join('\n');
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export function buildReviewInput({ role, agent, messages, reawake, reason }) {
|
|
184
|
+
return JSON.stringify({
|
|
185
|
+
persona: personaForReview(role),
|
|
186
|
+
currentContext: currentTurnContext(agent),
|
|
187
|
+
recentQQConversation: recentQQConversation(agent),
|
|
188
|
+
candidate: {
|
|
189
|
+
messages: messages.map((m) => ({ type: m.type, text: m.text })),
|
|
190
|
+
reawake: reawake ?? null,
|
|
191
|
+
reason: String(reason ?? '').slice(0, 1200),
|
|
192
|
+
},
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function parseFirstObject(text) {
|
|
197
|
+
const start = text.indexOf('{');
|
|
198
|
+
if (start < 0) return undefined;
|
|
199
|
+
let depth = 0;
|
|
200
|
+
let quoted = false;
|
|
201
|
+
let escaped = false;
|
|
202
|
+
for (let i = start; i < text.length; i++) {
|
|
203
|
+
const ch = text[i];
|
|
204
|
+
if (quoted) {
|
|
205
|
+
if (escaped) escaped = false;
|
|
206
|
+
else if (ch === '\\') escaped = true;
|
|
207
|
+
else if (ch === '"') quoted = false;
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
if (ch === '"') quoted = true;
|
|
211
|
+
else if (ch === '{') depth++;
|
|
212
|
+
else if (ch === '}' && --depth === 0) {
|
|
213
|
+
try { return JSON.parse(text.slice(start, i + 1)); } catch { return undefined; }
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
return undefined;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function normalizeReviewResult(value) {
|
|
220
|
+
if (!value || typeof value !== 'object' || typeof value.messages?.pass !== 'boolean'
|
|
221
|
+
|| typeof value.reawake?.reasonable !== 'boolean') {
|
|
222
|
+
throw new Error('审查模型没有返回规定的 JSON 结构');
|
|
223
|
+
}
|
|
224
|
+
return {
|
|
225
|
+
messages: {
|
|
226
|
+
pass: value.messages.pass,
|
|
227
|
+
reasons: Array.isArray(value.messages.reasons)
|
|
228
|
+
? value.messages.reasons.filter((x) => typeof x === 'string' && x.trim()).map((x) => x.trim()).slice(0, 6)
|
|
229
|
+
: [],
|
|
230
|
+
},
|
|
231
|
+
reawake: {
|
|
232
|
+
reasonable: value.reawake.reasonable,
|
|
233
|
+
reason: typeof value.reawake.reason === 'string' ? value.reawake.reason.trim() : '',
|
|
234
|
+
},
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** 一次独立的、无工具 LLM 审查调用。调用失败由上层按 fail-open 处理。 */
|
|
239
|
+
export async function reviewDirectorSend({ llm, agent, role, messages, reawake, reason, timeoutMs = 30_000 }) {
|
|
240
|
+
if (!llm || typeof llm.stream !== 'function') throw new Error('LLM 服务不可用');
|
|
241
|
+
const config = role?.proactive?.messageReview ?? {};
|
|
242
|
+
const route = resolveReviewRoute(config, agent);
|
|
243
|
+
if (!route) throw new Error('无法解析当前会话的审查 Provider/模型');
|
|
244
|
+
const controller = new AbortController();
|
|
245
|
+
const timer = setTimeout(() => controller.abort(new Error('消息审查超时')), timeoutMs);
|
|
246
|
+
let output = '';
|
|
247
|
+
let finish;
|
|
248
|
+
try {
|
|
249
|
+
const input = buildReviewInput({ role, agent, messages, reawake, reason });
|
|
250
|
+
const options = {
|
|
251
|
+
provider: route.provider,
|
|
252
|
+
model: route.model,
|
|
253
|
+
system: buildReviewSystemPrompt(),
|
|
254
|
+
messages: [{
|
|
255
|
+
id: randomUUID(), role: 'user',
|
|
256
|
+
content: [{ type: 'text', text: input }],
|
|
257
|
+
source: { kind: 'plugin', plugin: 'pygmalion' },
|
|
258
|
+
}],
|
|
259
|
+
temperature: 0,
|
|
260
|
+
maxTokens: 500,
|
|
261
|
+
signal: controller.signal,
|
|
262
|
+
};
|
|
263
|
+
for await (const chunk of llm.stream(options)) {
|
|
264
|
+
if (chunk?.type === 'text-delta') output += chunk.text;
|
|
265
|
+
else if (chunk?.type === 'block-end' && chunk.block?.type === 'text' && !output) output += chunk.block.text;
|
|
266
|
+
else if (chunk?.type === 'finish') finish = chunk.reason;
|
|
267
|
+
}
|
|
268
|
+
} finally {
|
|
269
|
+
clearTimeout(timer);
|
|
270
|
+
}
|
|
271
|
+
if (finish?.kind === 'error' || finish?.kind === 'aborted') throw new Error(finish.failure?.message ?? '消息审查失败');
|
|
272
|
+
if (finish?.kind === 'tool-calls' || finish?.kind === 'max-tokens') throw new Error(`消息审查异常结束:${finish.kind}`);
|
|
273
|
+
const parsed = parseFirstObject(output);
|
|
274
|
+
if (!parsed) throw new Error('无法解析审查模型返回的 JSON');
|
|
275
|
+
return { ...normalizeReviewResult(parsed), route };
|
|
276
|
+
}
|
package/src/persona.js
CHANGED
|
@@ -39,11 +39,12 @@ export function dataRoot() {
|
|
|
39
39
|
}
|
|
40
40
|
|
|
41
41
|
export const DEFAULT_MODEL = { provider: '', model: 'deepseek-v4-flash', vision: false };
|
|
42
|
-
export const DEFAULT_PROACTIVE = {
|
|
43
|
-
enabled: true, quietHours: [], maxWakeupsPerDay: 5,
|
|
44
|
-
lifeEnabled: true, archiveIdleMinutes: 45, eveningCheck: '20:00',
|
|
45
|
-
|
|
46
|
-
}
|
|
42
|
+
export const DEFAULT_PROACTIVE = {
|
|
43
|
+
enabled: true, quietHours: [], maxWakeupsPerDay: 5,
|
|
44
|
+
lifeEnabled: true, archiveIdleMinutes: 45, eveningCheck: '20:00',
|
|
45
|
+
messageReview: { enabled: true, provider: '', model: '' },
|
|
46
|
+
memeCollection: { enabled: false, intervalDays: 7, vision: { provider: '', model: '', apiUrl: '', apiKey: '' } },
|
|
47
|
+
};
|
|
47
48
|
|
|
48
49
|
/**
|
|
49
50
|
* 从 dsh session id 提取 QQ 目标 id(c2c=openid / group=群 id / channel=频道 id)。
|
|
@@ -259,17 +260,27 @@ export function roleWorkspace(roleId) { return join(roleDir(roleId), 'workspace'
|
|
|
259
260
|
function roleJson(roleId, name, fallback) { return readJson(join(roleDir(roleId), name), fallback); }
|
|
260
261
|
|
|
261
262
|
/** 聚合加载一个角色的全部配置。persona.json 缺失 → null(目录非角色)。 */
|
|
262
|
-
export async function loadRole(roleId) {
|
|
263
|
+
export async function loadRole(roleId) {
|
|
263
264
|
if (!roleId) return null;
|
|
264
265
|
const dir = roleDir(roleId);
|
|
265
266
|
if (!existsSync(join(dir, 'persona.json'))) return null;
|
|
266
267
|
const persona = await roleJson(roleId, 'persona.json', null);
|
|
267
268
|
if (!persona) return null;
|
|
268
|
-
|
|
269
|
+
const savedProactive = await roleJson(roleId, 'proactive.json', {});
|
|
270
|
+
return {
|
|
269
271
|
roleId,
|
|
270
272
|
persona,
|
|
271
273
|
model: { ...DEFAULT_MODEL, ...(await roleJson(roleId, 'model.json', {})) },
|
|
272
|
-
proactive: {
|
|
274
|
+
proactive: {
|
|
275
|
+
...DEFAULT_PROACTIVE,
|
|
276
|
+
...savedProactive,
|
|
277
|
+
messageReview: { ...DEFAULT_PROACTIVE.messageReview, ...(savedProactive.messageReview ?? {}) },
|
|
278
|
+
memeCollection: {
|
|
279
|
+
...DEFAULT_PROACTIVE.memeCollection,
|
|
280
|
+
...(savedProactive.memeCollection ?? {}),
|
|
281
|
+
vision: { ...DEFAULT_PROACTIVE.memeCollection.vision, ...(savedProactive.memeCollection?.vision ?? {}) },
|
|
282
|
+
},
|
|
283
|
+
},
|
|
273
284
|
binding: await roleJson(roleId, 'binding.json', {}),
|
|
274
285
|
state: await roleJson(roleId, 'state.json', {}),
|
|
275
286
|
voice: await roleJson(roleId, 'voice/mimo.json', {}),
|
|
@@ -389,22 +400,27 @@ export async function isRoleDirectorSession(roleId, sessionId) {
|
|
|
389
400
|
return role ? role.binding.openid === openid && Boolean(role.persona) : false;
|
|
390
401
|
}
|
|
391
402
|
|
|
392
|
-
/**
|
|
393
|
-
|
|
403
|
+
/**
|
|
404
|
+
* 安排角色延时唤醒(director_send reawake 参数)。写 role state.json.rewake。
|
|
405
|
+
* replaceId 只用于替换一次被发送审查退回时保留下来的兜底安排;普通调用仍可并存多个等待。
|
|
406
|
+
*/
|
|
407
|
+
export async function scheduleRewake(roleId, minutes, reason, { replaceId } = {}) {
|
|
394
408
|
const role = await loadRole(roleId);
|
|
395
409
|
if (!role) return { ok: false, atMs: 0, error: '角色不存在' };
|
|
396
410
|
const minutesN = Math.min(Math.max(Number(minutes) || 5, 1), 1440);
|
|
397
|
-
const atMs = Date.now() + minutesN * 60_000;
|
|
398
|
-
const createdAt = Date.now();
|
|
411
|
+
const atMs = Date.now() + minutesN * 60_000;
|
|
412
|
+
const createdAt = Date.now();
|
|
413
|
+
const id = randomBytes(8).toString('hex');
|
|
399
414
|
// 只保留「尚未到期」的等待;最多保留 MAX_PENDING-1 条旧待唤醒 + 本次,
|
|
400
415
|
// 防止堆积大量未来唤醒来回重复唤醒。(旧记录若曾触发过会在 heartbeat 侧被移除)
|
|
401
416
|
const MAX_PENDING = 5;
|
|
402
|
-
const state = { ...role.state, rewake: role.state.rewake ?? [] };
|
|
403
|
-
const pending = (Array.isArray(state.rewake) ? state.rewake : [])
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
}
|
|
417
|
+
const state = { ...role.state, rewake: role.state.rewake ?? [] };
|
|
418
|
+
const pending = (Array.isArray(state.rewake) ? state.rewake : [])
|
|
419
|
+
.filter((r) => r.atMs > createdAt && (replaceId === undefined || r.id !== replaceId));
|
|
420
|
+
state.rewake = [...pending.slice(-(MAX_PENDING - 1)), { id, atMs, reason: String(reason ?? '').trim() || '到时重新观察当前情境', createdAt }];
|
|
421
|
+
await saveRoleField(roleId, 'state', state);
|
|
422
|
+
return { ok: true, atMs, id };
|
|
423
|
+
}
|
|
408
424
|
|
|
409
425
|
// ---------------------------------------------------------------- 记忆 --
|
|
410
426
|
/** 人设 → memory-root 的 markdown(导演开场读)。 */
|