pygmalion 0.1.15 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +141 -70
  3. package/THIRD_PARTY.md +9 -0
  4. package/docs/ARCHITECTURE.md +66 -108
  5. package/docs/DEPLOY.md +33 -137
  6. package/docs/DEVELOPMENT.md +63 -0
  7. package/docs/DEVICE.md +56 -47
  8. package/docs/EXTENSIONS.md +176 -0
  9. package/docs/PRESET.md +21 -63
  10. package/docs/UPGRADE-0.2.md +52 -0
  11. package/package.json +52 -33
  12. package/preset/pygmalion-director/cordis.patch.yml +234 -0
  13. package/preset/pygmalion-director/pygmalion-tools.js +43 -41
  14. package/scripts/start-local-test.mjs +45 -45
  15. package/skills/pygmalion-life-scripts/SKILL.md +12 -0
  16. package/skills/pygmalion-meme-maintenance/SKILL.md +12 -0
  17. package/skills/pygmalion-memory-archive/SKILL.md +24 -0
  18. package/skills/pygmalion-toy-control/SKILL.md +16 -0
  19. package/src/agent-life.js +608 -606
  20. package/src/archive-tools.js +9 -0
  21. package/src/bot-factory.js +129 -311
  22. package/src/bots.js +264 -275
  23. package/src/channel-qq.js +262 -0
  24. package/src/config.js +69 -68
  25. package/src/delivery-receipt.js +36 -0
  26. package/src/delivery-scope.js +20 -0
  27. package/src/devices/manager.mjs +80 -570
  28. package/src/devices/monsterparty-controller.mjs +393 -0
  29. package/src/devices/{doc.mjs → monsterparty-doc.mjs} +60 -71
  30. package/src/devices/monsterparty.mjs +294 -294
  31. package/src/devices/pb.mjs +110 -110
  32. package/src/devices/registry.mjs +19 -0
  33. package/src/devices/script-helper.mjs +45 -0
  34. package/src/devices/scripts.mjs +109 -0
  35. package/src/devices/service.mjs +254 -0
  36. package/src/director-messages.js +35 -0
  37. package/src/dsh-runtime.js +17 -0
  38. package/src/extension-config.js +20 -0
  39. package/src/extensions.js +118 -0
  40. package/src/heartbeat.js +118 -97
  41. package/src/http-api.js +519 -509
  42. package/src/inbound.js +36 -207
  43. package/src/index.js +109 -37
  44. package/src/llm-provider.js +214 -171
  45. package/src/meme-worker.js +35 -39
  46. package/src/memebox.js +1 -1
  47. package/src/memory-recall.js +55 -0
  48. package/src/memory-write.js +136 -133
  49. package/src/peer-identity.js +26 -0
  50. package/src/persona.js +132 -69
  51. package/src/role-agent.js +155 -0
  52. package/src/role-runtime.js +65 -0
  53. package/src/roleplay-config.js +37 -0
  54. package/src/roleplay-format.js +37 -0
  55. package/src/roleplay-generation.js +36 -0
  56. package/src/roleplay-materials.js +113 -0
  57. package/src/roleplay-output.js +19 -0
  58. package/src/roleplay-parallel.js +239 -0
  59. package/src/roleplay-session.js +128 -0
  60. package/src/roleplay-worker.js +10 -0
  61. package/src/session-log.js +180 -172
  62. package/src/setup-agent.js +92 -100
  63. package/src/skills.js +97 -0
  64. package/src/slash-commands.js +155 -142
  65. package/src/speech-input.js +20 -0
  66. package/src/threads.js +2 -1
  67. package/src/tools.js +226 -254
  68. package/src/voice-defaults.js +13 -0
  69. package/src/voice-mimo.js +139 -125
  70. package/src/voice.js +200 -0
  71. package/src/wakeup.js +85 -66
  72. package/src/web-public/app.js +542 -382
  73. package/src/web-public/index.html +161 -158
  74. package/src/web-public/layout.css +7 -7
  75. package/src/web-public/style.css +12 -8
  76. package/src/web-server.js +161 -102
  77. package/src/worker-tools.js +18 -0
  78. package/templates/sample-life.mjs +59 -59
  79. package/templates/sample-toy.mjs +33 -33
  80. package/preset/pygmalion-director/agent.cordis.yml +0 -262
  81. package/preset/pygmalion-director/preset.yml +0 -3
  82. package/src/message-review.js +0 -276
@@ -0,0 +1,35 @@
1
+ /** director_send 消息规范化与基本协议校验;不作语言风格或 reawake 合理性审查。 */
2
+ const SYSTEM_MARKER_RE = /\[(?:时间线|唤醒事件|脚本事件|生活窗口|脚本审阅|归档任务|设备事件|HTTP 推送记录)\]/;
3
+ const CONTROL_WORD_RE = /\b(?:reawake|director_send)\b/i;
4
+
5
+ /** 把 director_send 的兼容输入规范化为内部消息对象。 */
6
+ export function normalizeDirectorMessages(raw) {
7
+ return (Array.isArray(raw) ? raw : []).map((item) => typeof item === 'string'
8
+ ? { type: 'text', text: item.trim() }
9
+ : {
10
+ type: item?.type === 'voice' ? 'voice' : 'text',
11
+ text: String(item?.text ?? '').trim(),
12
+ scene: String(item?.scene ?? '').trim(),
13
+ direction: String(item?.direction ?? '').trim(),
14
+ });
15
+ }
16
+
17
+ /**
18
+ * 不依赖模型的硬校验。空 messages 合法(只安排 reawake);数组中的空白项不合法。
19
+ * 返回具体的参数错误。
20
+ */
21
+ export function validateDirectorMessages(raw, messages = normalizeDirectorMessages(raw)) {
22
+ const issues = [];
23
+ const list = Array.isArray(raw) ? raw : [];
24
+ if (list.some((item) => (typeof item === 'string' ? item : item?.text) == null
25
+ || String(typeof item === 'string' ? item : item?.text).trim().length === 0)) {
26
+ issues.push('messages 中含空白消息;空数组可以表示本次不发送,但数组中的每一项都必须有内容');
27
+ }
28
+ for (let i = 0; i < messages.length; i++) {
29
+ const msg = messages[i];
30
+ const label = `第 ${i + 1} 条消息`;
31
+ if (CONTROL_WORD_RE.test(msg.text)) issues.push(`${label}包含内部控制词`);
32
+ if (SYSTEM_MARKER_RE.test(msg.text)) issues.push(`${label}包含系统情境标记`);
33
+ }
34
+ return [...new Set(issues)];
35
+ }
@@ -0,0 +1,17 @@
1
+ /** dsh 0.2.1 的公开持久化边界:不推导路径,不吞掉迁移或损坏错误。 */
2
+ export async function storedSession(persistence, sessionId) {
3
+ if (!persistence) return undefined;
4
+ if (typeof persistence.stat !== 'function') throw new Error('Pygmalion 需要 dsh 0.2.1-rc.2 的 sessionPersistence.stat');
5
+ return persistence.stat(sessionId);
6
+ }
7
+
8
+ export async function readSessionEvents(persistence, sessionId) {
9
+ if (!persistence || !sessionId) throw new Error('读取聊天记录缺少持久化服务或 sessionId');
10
+ const reader = await persistence.open(sessionId, 'read');
11
+ try { return (await reader.read()).events; }
12
+ finally { await reader.close(); }
13
+ }
14
+
15
+ export function sessionMissing(error) {
16
+ return error?.name === 'SessionPersistenceNotFoundError';
17
+ }
@@ -0,0 +1,20 @@
1
+ /** 扩展配置的有限字段类型;不包含任何厂商或设备能力。 */
2
+ export function defaults(descriptor, values) {
3
+ return { ...Object.fromEntries(descriptor.fields.filter(field => field.default !== undefined).map(field => [field.key, field.default])), ...values };
4
+ }
5
+
6
+ export function validate(descriptor, values, required) {
7
+ for (const field of descriptor.fields) {
8
+ const value = values[field.key];
9
+ if (value === undefined || value === null || typeof value === 'string' && !value.trim()) {
10
+ if (required && field.required) throw new Error(`请配置${field.label}`);
11
+ continue;
12
+ }
13
+ if (field.type === 'boolean' ? typeof value !== 'boolean'
14
+ : field.type === 'audio' ? typeof value !== 'object' || typeof value.file !== 'string'
15
+ : typeof value !== 'string') throw new Error(`${field.label}格式不正确`);
16
+ if (field.type === 'select' && !field.options.some(option => option.value === value)) throw new Error(`${field.label}选项不存在`);
17
+ }
18
+ descriptor.validate?.(values, { required });
19
+ }
20
+
@@ -0,0 +1,118 @@
1
+ /** 公开扩展描述契约;注册不执行网络请求,失效由同一个实例句柄表示。 */
2
+ const ID = /^[a-z][a-z0-9._-]*$/;
3
+ const FIELD = /^[a-zA-Z][a-zA-Z0-9_-]*$/;
4
+ const TYPES = new Set(['text', 'secret', 'boolean', 'select', 'audio']);
5
+
6
+ /** @param {{apiVersion:1,id:string,name:string,fields?:Array<object>,create:Function}} definition */
7
+ function defineDescriptor(definition, type) {
8
+ if (definition?.apiVersion !== 1 || !ID.test(definition.id) || !definition.name || typeof definition.create !== 'function') {
9
+ throw new Error(`${type} 描述必须提供 apiVersion:1、稳定 id、名称和 create`);
10
+ }
11
+ const keys = new Set();
12
+ const fields = (definition.fields ?? []).map(field => {
13
+ if (!FIELD.test(field.key) || keys.has(field.key) || !TYPES.has(field.type) || !field.label) throw new Error(`${type} 配置字段无效或重复`);
14
+ if (field.type === 'select' && (!Array.isArray(field.options) || !field.options.every(option => typeof option.value === 'string' && typeof option.label === 'string'))) throw new Error(`${type} 选项无效`);
15
+ if (field.type === 'secret' && field.default !== undefined) throw new Error('凭据字段不能包含公开默认值');
16
+ keys.add(field.key);
17
+ return Object.freeze({ ...field, ...(field.options ? { options: Object.freeze(field.options.map(option => Object.freeze({ ...option }))) } : {}) });
18
+ });
19
+ return Object.freeze({ ...definition, fields: Object.freeze(fields) });
20
+ }
21
+
22
+ export function defineTtsProvider(definition) { return defineDescriptor(definition, 'TTS'); }
23
+
24
+ /** 通信实现只声明配置、身份作用域与连接工厂;角色模型/记忆不归适配器。 */
25
+ export function defineChannelAdapter(definition) {
26
+ const descriptor = defineDescriptor(definition, '通信适配器');
27
+ if (typeof descriptor.accountId !== 'function' || descriptor.fields.some(field => field.type === 'audio')) throw new Error('通信实现须声明 accountId(config),配置不支持音频字段');
28
+ return descriptor;
29
+ }
30
+
31
+ /** 驱动声明一次操作,工具与脚本使用相同的参数和执行函数。 */
32
+ export function defineDeviceDriver(definition) {
33
+ const descriptor = defineDescriptor(definition, '设备驱动');
34
+ if (descriptor.fields.some(field => field.type === 'audio')) throw new Error('设备配置不支持音频字段');
35
+ if (!ID.test(definition.skill?.name) || !definition.skill.description || typeof definition.skill.path !== 'string') {
36
+ throw new Error('设备驱动必须配套提供稳定名称、说明和本地 skill 路径');
37
+ }
38
+ const operations = Object.fromEntries(Object.entries(definition.operations ?? {}).map(([id, operation]) => {
39
+ if (!ID.test(id) || id.replace(/[.-]/g, '_') === 'run_script' || !operation.description || typeof operation.execute !== 'function' || operation.parameters?.type !== 'object') {
40
+ throw new Error(`设备操作无效:${id}`);
41
+ }
42
+ return [id, Object.freeze({ ...operation })];
43
+ }));
44
+ for (const alias of definition.scriptAliases ?? []) {
45
+ if (!FIELD.test(alias.name) || ['device', 'process', 'globalThis'].includes(alias.name)) throw new Error('脚本别名无效');
46
+ for (const [name, target] of Object.entries(alias.methods ?? {})) {
47
+ if (!FIELD.test(name) || !operations[target] && !['$sleep', '$wake'].includes(target)) throw new Error('脚本别名方法无效');
48
+ }
49
+ }
50
+ return Object.freeze({ ...descriptor, skill: Object.freeze({ ...definition.skill }), operations: Object.freeze(operations) });
51
+ }
52
+
53
+ export function deviceToolName(driverId, operationId) {
54
+ return `device_${driverId.replace(/[.-]/g, '_')}__${operationId.replace(/[.-]/g, '_')}`;
55
+ }
56
+
57
+ export function createExtensionRegistry({ assertDeviceOperation, assertDeviceDriver } = {}) {
58
+ const tts = new Map();
59
+ const drivers = new Map();
60
+ const channels = new Map();
61
+ const listeners = new Set();
62
+ const changed = () => { for (const listener of listeners) { try { listener(); } catch { /* 目录订阅者失败不改变注册结果 */ } } };
63
+ let disposed = false;
64
+ const register = (entries, descriptor, type) => {
65
+ if (disposed) throw new Error('扩展服务已关闭');
66
+ if (entries.has(descriptor.id)) throw new Error(`${type} ID 重复:${descriptor.id}`);
67
+ const lifetime = new AbortController();
68
+ const release = () => {
69
+ if (entries.get(descriptor.id) === entry) entries.delete(descriptor.id);
70
+ lifetime.abort(new Error(`${type} 扩展已卸载`));
71
+ changed();
72
+ };
73
+ const entry = Object.freeze({ descriptor, signal: lifetime.signal, release });
74
+ entries.set(descriptor.id, entry);
75
+ changed();
76
+ return release;
77
+ };
78
+ return {
79
+ subscribe(listener) { listeners.add(listener); return () => listeners.delete(listener); },
80
+ registerChannelAdapter: definition => register(channels, defineChannelAdapter(definition), '通信适配器'),
81
+ getChannelAdapter: id => channels.get(id),
82
+ listChannelAdapters: () => [...channels.values()].map(({ descriptor }) => ({ id: descriptor.id, name: descriptor.name, fields: descriptor.fields })),
83
+ registerTtsProvider(definition) {
84
+ return register(tts, defineTtsProvider(definition), 'TTS');
85
+ },
86
+ getTtsProvider: id => tts.get(id),
87
+ listTtsProviders: () => [...tts.values()].map(({ descriptor }) => ({
88
+ id: descriptor.id, name: descriptor.name, fields: descriptor.fields,
89
+ })),
90
+ registerDeviceDriver(definition) {
91
+ const descriptor = defineDeviceDriver(definition);
92
+ assertDeviceDriver?.(descriptor);
93
+ if (!assertDeviceOperation) throw new Error('当前宿主缺少设备操作 schema 校验能力');
94
+ const occupied = new Set([...drivers.values()].flatMap(({ descriptor: item }) => ['run_script', ...Object.keys(item.operations)].map(id => deviceToolName(item.id, id))));
95
+ const scriptTool = deviceToolName(descriptor.id, 'run_script');
96
+ if (occupied.has(scriptTool)) throw new Error(`设备工具名称冲突:${scriptTool}`);
97
+ occupied.add(scriptTool);
98
+ for (const [id, operation] of Object.entries(descriptor.operations)) {
99
+ assertDeviceOperation(operation);
100
+ const tool = deviceToolName(descriptor.id, id);
101
+ if (occupied.has(tool)) throw new Error(`设备工具名称冲突:${tool}`);
102
+ occupied.add(tool);
103
+ }
104
+ if ([...drivers.values()].some(item => item.descriptor.skill.name === descriptor.skill.name)) throw new Error('设备 skill 名称重复');
105
+ return register(drivers, descriptor, '设备驱动');
106
+ },
107
+ getDeviceDriver: id => drivers.get(id),
108
+ listDeviceDrivers: () => [...drivers.values()].map(({ descriptor }) => ({
109
+ id: descriptor.id, name: descriptor.name, fields: descriptor.fields,
110
+ skill: { name: descriptor.skill.name, description: descriptor.skill.description },
111
+ operations: Object.entries(descriptor.operations).map(([id, operation]) => ({ id, description: operation.description })),
112
+ })),
113
+ dispose() {
114
+ disposed = true;
115
+ for (const entry of [...tts.values(), ...drivers.values(), ...channels.values()]) entry.release();
116
+ },
117
+ };
118
+ }
package/src/heartbeat.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { bindingStamp } from './peer-identity.js';
1
2
  /**
2
3
  * Pygmalion 内置心跳:自动对每个「bot 管线服务的角色」执行
3
4
  * ① 主动唤醒(角色日程 / 今日未联系问候)
@@ -9,10 +10,9 @@
9
10
  import { join } from 'node:path';
10
11
  import { readFile, readdir } from 'node:fs/promises';
11
12
  import { listRunningLifeScripts, recoverLifeScripts, pruneDeadLifeScripts } from './agent-life.js';
12
- import { wakeupSession, archiveWakeup, buildScriptReviewContext } from './wakeup.js';
13
+ import { wakeupSession, archiveWakeup, buildScriptReviewContext } from './wakeup.js';
13
14
  import { classifyStagedMemes, collectMemes, resolveVisionConfig, withMemeLock } from './meme-worker.js';
14
15
  import { listMemes } from './memebox.js';
15
- import { activeSessionFile } from './active-session.js';
16
16
  import { refreshRawRecordFromSession } from './memory-write.js';
17
17
  import { inQuietHours } from './quiet-hours.js';
18
18
  import { effectiveSessionId } from './inbound.js';
@@ -45,14 +45,21 @@ export function createHeartbeatScheduler(deps) {
45
45
  const currentPipelines = () => (typeof deps.pipelines === 'function' ? deps.pipelines() : deps.pipelines);
46
46
  let timer = null;
47
47
  let stopped = false;
48
+ let running = null;
49
+ const memeJobs = new Map();
50
+ const lifetime = new AbortController();
48
51
  // 每个 dsh 进程启动后首个心跳 tick 视为「重启后首次」,无视 lastLifeWarnAt 旧节流:
49
52
  // 否则重启前设下的节流会跨重启压制非零性提示(例:重启前刚唤醒过 → 重启后要等整个
50
53
  // 窗口才再通知,dsh 一直不知道脚本已经没了)。
51
54
  let freshLife = true;
52
55
 
53
56
  /** 每个 bot 管线构建 wakeupSession 依赖(含该管线的 botId/roleId/线程/路由/活动时间/生活脚本状态)。 */
54
- function wakeBaseFor(p) {
57
+ function wakeBaseFor(p, expectedRole) {
55
58
  return {
59
+ assertCurrent: expectedRole ? async () => {
60
+ if (stopped || bindingStamp(await persona.loadRole(p.roleId)) !== bindingStamp(expectedRole)) throw new Error('角色状态已改变,本次后台任务已取消');
61
+ } : undefined,
62
+ sessionIdFor: p.sessionIdFor,
56
63
  threads: p.threads,
57
64
  routes: p.routes,
58
65
  ensureAgent: (sid) => p.inbound.ensureAgent(sid),
@@ -74,6 +81,8 @@ export function createHeartbeatScheduler(deps) {
74
81
 
75
82
  function archiveBaseFor(p) {
76
83
  return {
84
+ subagents,
85
+ sessionIdFor: p.sessionIdFor,
77
86
  threads: p.threads,
78
87
  ensureAgent: (sid) => p.inbound.ensureAgent(sid),
79
88
  persona,
@@ -83,7 +92,7 @@ export function createHeartbeatScheduler(deps) {
83
92
  };
84
93
  }
85
94
 
86
- /** 收集「有绑定 openid、该 bot 管线服务的角色」上下文(无 openid 无法联系则跳过)。 */
95
+ /** 收集「有绑定 peerId、该 bot 管线服务的角色」上下文(无 peerId 无法联系则跳过)。 */
87
96
  async function roleContexts() {
88
97
  const out = [];
89
98
  for (const p of currentPipelines()) {
@@ -92,43 +101,44 @@ export function createHeartbeatScheduler(deps) {
92
101
  log?.warn?.('pygmalion heartbeat: role %s missing (pipeline %s)', p.roleId, p.botId);
93
102
  continue;
94
103
  }
95
- const openid = role.binding?.openid;
96
- if (!openid) continue;
97
- out.push({ pipeline: p, role, openid });
104
+ const target = p.boundTarget ? await p.boundTarget(role) : role.binding?.openid ? {kind:'c2c',userId:role.binding.openid} : undefined;
105
+ if (!target) continue;
106
+ const peerId = target.identity?.peerId ?? target.userId;
107
+ out.push({ pipeline: p, role, peerId, target });
98
108
  }
99
109
  return out;
100
110
  }
101
111
 
102
- /** 各 c2c openid 的最后用户活动时间(来自该管线路由存储,纯用户消息驱动)。 */
103
- function lastActivityByOpenid(routes) {
112
+ /** 各 c2c peerId 的最后用户活动时间(来自该管线路由存储,纯用户消息驱动)。 */
113
+ function lastActivityByPeer(routes) {
104
114
  const map = {};
105
115
  for (const { record } of routes.entries()) {
106
116
  const t = record?.target;
107
- if (t?.kind === 'c2c' && t.userId && typeof record.lastMsgAt === 'number')
108
- map[t.userId] = Math.max(map[t.userId] ?? 0, record.lastMsgAt);
117
+ const peerId=t?.identity?.peerId ?? (t?.kind==='c2c'?t.userId:undefined);
118
+ if (peerId && typeof record.lastMsgAt === 'number') map[peerId]=Math.max(map[peerId]??0,record.lastMsgAt);
109
119
  }
110
120
  return map;
111
121
  }
112
122
 
113
123
  /** 兜底:每 tick 从活跃会话 session log 提取写日期层原始记录(主触发在 inbound / director_send)。 */
114
- async function refreshRawRecord({ role, openid, pipeline }) {
115
- const counter = pipeline.threads?.current(`c2c:${openid}`) ?? 0;
116
- const file = activeSessionFile({ openid, threadCounter: counter, workspace: role.workspace, dshHome, botId: pipeline.botId });
124
+ async function refreshRawRecord({ role, peerId, pipeline, target }) {
125
+ const counter = pipeline.threads?.current(targetKey(target)) ?? 0;
126
+ const sessionId = pipeline.sessionIdFor?.(target) ?? effectiveSessionId(target, counter, pipeline.botId);
117
127
  const charLabel = role.persona?.name || role.roleId || '角色';
118
- await refreshRawRecordFromSession({ workspace: role.workspace, sessionFile: file, charLabel, log });
128
+ await refreshRawRecordFromSession({ workspace: role.workspace, sessionId, persistence: deps.sessionPersistence, charLabel, log });
119
129
  }
120
130
 
121
131
  /** 收集「需要主动唤醒」的任务。 */
122
132
  async function computeWakeups(ctxs, now) {
123
133
  const out = [];
124
134
  for (const ctx of ctxs) {
125
- const { role, openid, pipeline } = ctx;
135
+ const { role, peerId, pipeline } = ctx;
126
136
  const pr = role.proactive || {};
127
137
  if (pr.enabled === false) continue;
128
138
  if (inQuietHours(pr.quietHours || [], now)) continue;
129
139
  // 未激活:从没聊过一次的角色不主动唤醒(无用户消息历史 = 未激活)。
130
- const lastBy = lastActivityByOpenid(pipeline.routes);
131
- const last = lastBy[openid];
140
+ const lastBy = lastActivityByPeer(pipeline.routes);
141
+ const last = lastBy[peerId];
132
142
  if (last === undefined) continue;
133
143
  const state = role.state || {};
134
144
  const todayCount = (state.wakeDates && state.wakeDates[today(now)]) || 0;
@@ -158,13 +168,13 @@ export function createHeartbeatScheduler(deps) {
158
168
  const ts = Date.now();
159
169
  const out = [];
160
170
  for (const ctx of ctxs) {
161
- const { role, openid, pipeline } = ctx;
171
+ const { role, peerId, pipeline } = ctx;
162
172
  const pr = role.proactive || {};
163
173
  // 免打扰时段不唤醒 dsh 归档(归档也消耗 dsh 上下文;等安静时段结束后的下一 tick 再处理)。
164
174
  if (inQuietHours(pr.quietHours || [], now)) continue;
165
175
  const idleLimit = pr.archiveIdleMinutes ?? config.heartbeat?.archiveIdleMinutes ?? 45;
166
176
  if (!idleLimit) continue;
167
- const last = lastActivityByOpenid(pipeline.routes)[openid];
177
+ const last = lastActivityByPeer(pipeline.routes)[peerId];
168
178
  if (last === undefined) continue;
169
179
  // 上次归档后用户没有新消息 → 没有新内容,不重复唤醒 dsh 归档(避免每日空跑)。
170
180
  if (typeof role.state?.lastArchiveAt === 'number' && last <= role.state.lastArchiveAt) continue;
@@ -186,10 +196,9 @@ export function createHeartbeatScheduler(deps) {
186
196
 
187
197
  /** 取角色导演 agent 作为 subagent 父(谱系锚;导演不参与处理)。 */
188
198
  async function parentAgentFor(ctx) {
189
- const { openid, pipeline } = ctx;
190
- const target = { kind: 'c2c', userId: openid };
199
+ const { target, pipeline } = ctx;
191
200
  const thread = pipeline.threads.current(targetKey(target));
192
- const sessionId = effectiveSessionId(target, thread, pipeline.botId);
201
+ const sessionId = pipeline.sessionIdFor?.(target) ?? effectiveSessionId(target, thread, pipeline.botId);
193
202
  return pipeline.inbound.ensureAgent(sessionId);
194
203
  }
195
204
 
@@ -216,18 +225,17 @@ export function createHeartbeatScheduler(deps) {
216
225
  // 与委托 subagent_meme 工具互斥:同角色不并发写库。
217
226
  await withMemeLock(role.roleId, async () => {
218
227
  if (stagedCount > 0) {
219
- const r = await classifyStagedMemes({ subagents, parentAgent, workspace, vision, log });
228
+ const r = await classifyStagedMemes({ subagents, parentAgent, workspace, vision, log, signal:lifetime.signal });
220
229
  if (!r.ok) log?.warn?.('pygmalion meme classify %s failed: %o', role.roleId, r.error);
221
230
  }
222
231
  if (collectDue) {
223
232
  const r = await collectMemes({
224
- subagents, parentAgent, workspace, vision, log,
233
+ subagents, parentAgent, workspace, vision, log, signal:lifetime.signal,
225
234
  goal: role.persona?.name ? `为「${role.persona.name}」收集一组风格匹配的表情包` : undefined,
226
235
  count: '5~10',
227
236
  });
228
237
  if (r.ok) {
229
- const st = { ...(role.state || {}), memeLastRunAt: Date.now() };
230
- await persona.saveRoleField(role.roleId, 'state', st);
238
+ await persona.updateRoleState(role.roleId, state => ({...state,memeLastRunAt:Date.now()}));
231
239
  }
232
240
  }
233
241
  });
@@ -240,12 +248,10 @@ export function createHeartbeatScheduler(deps) {
240
248
  /** 记一次主动唤醒(写角色 state.json.wakeDates/eveningSentDate)。 */
241
249
  async function bumpState(ctx, { evening = false }) {
242
250
  try {
243
- const state = { ...(ctx.role.state || {}) };
244
- const key = today();
245
- state.lastWakeupAt = new Date().toISOString();
246
- state.wakeDates = { ...(state.wakeDates || {}), [key]: ((state.wakeDates || {})[key] || 0) + 1 };
247
- if (evening) state.eveningSentDate = key;
248
- await persona.saveRoleField(ctx.role.roleId, 'state', state);
251
+ await persona.updateRoleState(ctx.role.roleId,state=>{
252
+ const key=today();
253
+ return {...state,lastWakeupAt:new Date().toISOString(),wakeDates:{...state.wakeDates,[key]:(state.wakeDates?.[key]??0)+1},...(evening?{eveningSentDate:key}:{})};
254
+ });
249
255
  } catch (e) { log?.warn?.('heartbeat state write failed: %o', e); }
250
256
  }
251
257
 
@@ -253,57 +259,60 @@ export function createHeartbeatScheduler(deps) {
253
259
  async function rewakeTick(ctxs, now) {
254
260
  const ts = now.getTime();
255
261
  for (const ctx of ctxs) {
256
- const { role, openid, pipeline } = ctx;
262
+ const { role, peerId, pipeline } = ctx;
257
263
  const state = { ...(role.state || {}) };
258
264
  if (!Array.isArray(state.rewake) || !state.rewake.length) continue;
259
265
  const due = state.rewake.filter((r) => r.atMs <= ts);
260
266
  if (!due.length) continue;
261
- const lastBy = lastActivityByOpenid(pipeline.routes);
267
+ const completed = new Set();
268
+ const lastBy = lastActivityByPeer(pipeline.routes);
262
269
  for (const r of due) {
263
- const last = lastBy[openid];
270
+ const last = lastBy[peerId];
264
271
  // 取消语义:从「安排时刻 createdAt」起,用户只要发过任何消息(哪怕在到点之前),
265
272
  // 这次等待就自然完成——不再唤醒,节省一次无效调用。
266
273
  const bound = r.createdAt ?? r.atMs;
267
274
  if (last !== undefined && last >= bound) {
268
275
  log?.info?.('pygmalion rewake cancelled for role %s (user replied during wait)', role.roleId);
269
- state.rewake = state.rewake.filter((x) => x !== r);
276
+ completed.add(r.id);
270
277
  continue;
271
278
  }
272
279
  // 免打扰时段:rewake 到期也不立即唤醒,留在队列等安静时段结束后的下一 tick 再发。
273
280
  if (inQuietHours(role.proactive?.quietHours || [], now)) continue;
274
281
  try {
275
- await wakeupSession(wakeBaseFor(pipeline), {
276
- target: { kind: 'c2c', userId: openid },
277
- reason: 'reawake 到期,重新审视当前情境',
278
- memoryHint: `此前留下的观察线索:${r.reason}。用户在这段时间没有发消息。`
279
- + '这只是供此刻重新判断的线索,不是待执行的发言计划,也不表示现在必须开口。',
280
- });
282
+ const result = await wakeupSession(wakeBaseFor(pipeline, role), {
283
+ target: ctx.target,
284
+ reason: 'reawake 到期,重新审视当前情境',
285
+ memoryHint: `此前留下的观察线索:${r.reason}。用户在这段时间没有发消息。`
286
+ + '这只是供此刻重新判断的线索,不是待执行的发言计划,也不表示现在必须开口。',
287
+ });
288
+ if (result?.woken) completed.add(r.id);
281
289
  log?.info?.('pygmalion heartbeat: rewake due for role %s', role.roleId);
282
290
  } catch (e) { log?.warn?.('pygmalion rewake %s failed: %o', role.roleId, e); }
283
- state.rewake = state.rewake.filter((x) => x !== r);
284
291
  }
285
- try { await persona.saveRoleField(role.roleId, 'state', state); } catch { /* ignore */ }
292
+ if (completed.size) {
293
+ try { await persona.updateRoleState(role.roleId,state=>({...state,rewake:(state.rewake??[]).filter(item=>!completed.has(item.id))})); } catch { /* ignore */ }
294
+ }
286
295
  }
287
296
  }
288
297
 
289
298
  /**
290
- * ③ 非零性检查:每个绑定 openid 的角色必须「至少有一个生活脚本在运行」。
299
+ * ③ 非零性检查:每个绑定 peerId 的角色必须「至少有一个生活脚本在运行」。
291
300
  * 有脚本在跑 → 角色生活正常,不打搅 dsh;没有任何脚本在运行(非零性破坏)→
292
301
  * 节流(warnIntervalMs)后唤醒 dsh,让它创作角色生活经历并程序化为脚本(life_run 启动)。
293
302
  * 插件不限制脚本运行时长/次数;「非零」由 dsh 保证。撞车/静默由 wakeupSession 处理。
294
303
  */
295
- async function lifeTick(ctxs, now) {
304
+ async function lifeTick(ctxs, now) {
296
305
  if (config.heartbeat?.lifeEnabled === false) return;
297
306
  const ts = now.getTime();
298
307
  const warnIntervalMs = config.heartbeat?.lifeIntervalMs ?? 3 * 3600 * 1000;
299
308
  for (const ctx of ctxs) {
300
- const { role, openid, pipeline } = ctx;
309
+ const { role, peerId, pipeline } = ctx;
301
310
  const pr = role.proactive || {};
302
311
  if (pr.lifeEnabled === false) continue;
303
312
  // 免打扰时段不唤醒(非零性提醒也等安静时段结束)。
304
313
  if (inQuietHours(pr.quietHours || [], now)) continue;
305
314
  // 未激活:从没聊过一次的角色不检查(无用户消息历史 = 未激活)。
306
- if (lastActivityByOpenid(pipeline.routes)[openid] === undefined) continue;
315
+ if (lastActivityByPeer(pipeline.routes)[peerId] === undefined) continue;
307
316
  await recoverLifeScripts(role.workspace);
308
317
  await pruneDeadLifeScripts(role.workspace);
309
318
  const running = await listRunningLifeScripts(role.workspace);
@@ -311,46 +320,46 @@ export function createHeartbeatScheduler(deps) {
311
320
  const state = { ...(role.state || {}) };
312
321
  if (!freshLife && ts - (state.lastLifeWarnAt ?? 0) < warnIntervalMs) continue; // 节流,防每 tick 轰炸
313
322
  try {
314
- const r = await wakeupSession(wakeBaseFor(pipeline), {
315
- target: { kind: 'c2c', userId: openid },
323
+ const r = await wakeupSession(wakeBaseFor(pipeline, role), {
324
+ target: ctx.target,
316
325
  reason: '生活脚本未在运行(非零性破坏)',
317
326
  kind: 'life',
318
327
  });
319
328
  if (r?.ok === true) {
320
329
  state.lastLifeWarnAt = ts;
321
- await persona.saveRoleField(role.roleId, 'state', state);
330
+ await persona.updateRoleState(role.roleId,current=>({...current,lastLifeWarnAt:ts}));
322
331
  log?.info?.('pygmalion heartbeat: life nonzero warn %s (no script running)', role.roleId);
323
332
  }
324
333
  } catch (e) { log?.warn?.('pygmalion heartbeat life %s failed: %o', role.roleId, e); }
325
334
  }
326
335
  // 首个 tick 已执行(无论是否唤醒),之后恢复节流。
327
336
  freshLife = false;
328
- }
329
-
330
- /** 每日独立审阅:不以运行脚本数量作为触发条件。 */
331
- async function scriptReviewTick(ctxs, now) {
332
- const at = String(config.heartbeat?.scriptReviewTime ?? '02:00').trim();
333
- if (!at || !/^([01]\d|2[0-3]):[0-5]\d$/.test(at)) return;
334
- if (nowHm(now) < at) return;
335
- const date = today(now);
336
- for (const ctx of ctxs) {
337
- const { role, openid, pipeline } = ctx;
338
- if (role.proactive?.lifeEnabled === false) continue;
339
- if (lastActivityByOpenid(pipeline.routes)[openid] === undefined) continue;
340
- if (role.state?.lastScriptReviewDate === date) continue;
341
- try {
342
- const text = buildScriptReviewContext({ personaName: role.persona?.name, now });
343
- const r = await wakeupSession(wakeBaseFor(pipeline), {
344
- target: { kind: 'c2c', userId: openid }, reason: '每日脚本审阅', contextText: text, force: true,
345
- });
346
- // wakeupSession 因撞车跳过时不记完成,下一 tick 会重试;成功(即使导演沉默)才算审阅已送达。
347
- if (r?.ok) {
348
- await persona.saveRoleField(role.roleId, 'state', { ...(role.state || {}), lastScriptReviewDate: date });
349
- log?.info?.('pygmalion heartbeat: daily script review %s', role.roleId);
350
- }
351
- } catch (e) { log?.warn?.('pygmalion heartbeat script review %s failed: %o', role.roleId, e); }
352
- }
353
- }
337
+ }
338
+
339
+ /** 每日独立审阅:不以运行脚本数量作为触发条件。 */
340
+ async function scriptReviewTick(ctxs, now) {
341
+ const at = String(config.heartbeat?.scriptReviewTime ?? '02:00').trim();
342
+ if (!at || !/^([01]\d|2[0-3]):[0-5]\d$/.test(at)) return;
343
+ if (nowHm(now) < at) return;
344
+ const date = today(now);
345
+ for (const ctx of ctxs) {
346
+ const { role, peerId, pipeline } = ctx;
347
+ if (role.proactive?.lifeEnabled === false) continue;
348
+ if (lastActivityByPeer(pipeline.routes)[peerId] === undefined) continue;
349
+ if (role.state?.lastScriptReviewDate === date) continue;
350
+ try {
351
+ const text = buildScriptReviewContext({ personaName: role.persona?.name, now });
352
+ const r = await wakeupSession(wakeBaseFor(pipeline, role), {
353
+ target: ctx.target, reason: '每日脚本审阅', contextText: text, force: true,
354
+ });
355
+ // wakeupSession 因撞车跳过时不记完成,下一 tick 会重试;成功(即使导演沉默)才算审阅已送达。
356
+ if (r?.ok) {
357
+ await persona.updateRoleState(role.roleId,state=>({...state,lastScriptReviewDate:date}));
358
+ log?.info?.('pygmalion heartbeat: daily script review %s', role.roleId);
359
+ }
360
+ } catch (e) { log?.warn?.('pygmalion heartbeat script review %s failed: %o', role.roleId, e); }
361
+ }
362
+ }
354
363
 
355
364
  /**
356
365
  * ⑤ 免打扰时段推迟的唤醒:脚本在安静时段调用 /wakeup 时,插件把唤醒写入
@@ -359,31 +368,32 @@ export function createHeartbeatScheduler(deps) {
359
368
  */
360
369
  async function deferredWakeupTick(ctxs, now) {
361
370
  for (const ctx of ctxs) {
362
- const { role, openid, pipeline } = ctx;
371
+ const { role, peerId, pipeline } = ctx;
363
372
  const state = role.state || {};
364
373
  if (!state.deferredWakeup) continue;
365
374
  if (inQuietHours(role.proactive?.quietHours || [], now)) continue; // 仍在安静时段,继续等
366
375
  const dw = state.deferredWakeup;
367
376
  try {
368
- const r = await wakeupSession(wakeBaseFor(pipeline), {
369
- target: { kind: 'c2c', userId: openid },
377
+ const r = await wakeupSession(wakeBaseFor(pipeline, role), {
378
+ target: ctx.target,
370
379
  reason: dw.reason || '免打扰时段推迟的脚本唤醒',
371
- memoryHint: dw.memoryHint,
372
- contextText: dw.contextText,
380
+ memoryHint: dw.memoryHint,
381
+ contextText: dw.contextText,
373
382
  kind: dw.kind,
374
383
  mood: dw.mood,
375
384
  topic: dw.topic,
376
385
  force: dw.force,
377
386
  });
387
+ if (!r?.woken) continue;
378
388
  log?.info?.('pygmalion heartbeat: deferred wakeup fired %s (ok=%s)', role.roleId, Boolean(r?.ok));
379
- } catch (e) { log?.warn?.('pygmalion deferred wakeup %s failed: %o', role.roleId, e); }
380
- const st = { ...state, deferredWakeup: undefined };
381
- if (dw.kind === 'script-hook') st.lastScriptWakeAt = Date.now();
382
- try { await persona.saveRoleField(role.roleId, 'state', st); } catch { /* ignore */ }
389
+ } catch (e) { log?.warn?.('pygmalion deferred wakeup %s failed: %o', role.roleId, e); continue; }
390
+ const current = await persona.loadRole(role.roleId);
391
+ if (current?.state?.deferredWakeup?.atMs !== dw.atMs) continue;
392
+ try { await persona.updateRoleState(role.roleId,state=>state.deferredWakeup?.atMs===dw.atMs?({...state,deferredWakeup:undefined,...(dw.kind==='script-hook'?{lastScriptWakeAt:Date.now()}:{})}):state); } catch { /* ignore */ }
383
393
  }
384
394
  }
385
395
 
386
- async function runOnce() {
396
+ async function tick() {
387
397
  if (stopped) return;
388
398
  const ctxs = await roleContexts();
389
399
  const now = new Date();
@@ -394,8 +404,8 @@ export function createHeartbeatScheduler(deps) {
394
404
  }
395
405
  for (const w of await computeWakeups(ctxs, now)) {
396
406
  try {
397
- const r = await wakeupSession(wakeBaseFor(w.ctx.pipeline), {
398
- target: { kind: 'c2c', userId: w.ctx.openid },
407
+ const r = await wakeupSession(wakeBaseFor(w.ctx.pipeline, w.ctx.role), {
408
+ target: w.ctx.target,
399
409
  reason: w.reason,
400
410
  memoryHint: w.memoryHint,
401
411
  });
@@ -403,23 +413,34 @@ export function createHeartbeatScheduler(deps) {
403
413
  log?.info?.('pygmalion heartbeat: wakeup %s (%s) ok=%s', w.ctx.role.roleId, w.rule, Boolean(r?.ok));
404
414
  } catch (e) { log?.warn?.('pygmalion heartbeat wakeup %s failed: %o', w.ctx.role.roleId, e); }
405
415
  }
406
- await lifeTick(ctxs, now);
407
- await scriptReviewTick(ctxs, now);
416
+ await lifeTick(ctxs, now);
417
+ await scriptReviewTick(ctxs, now);
408
418
  await rewakeTick(ctxs, now);
409
419
  await deferredWakeupTick(ctxs, now);
410
420
  for (const a of await computeArchives(ctxs, now)) {
411
421
  try {
412
- await archiveWakeup(archiveBaseFor(a.ctx.pipeline), { target: { kind: 'c2c', userId: a.ctx.openid }, date: a.date });
422
+ const result = await archiveWakeup(archiveBaseFor(a.ctx.pipeline), { target: a.ctx.target, date: a.date });
423
+ if (!result.ok) continue;
413
424
  // 记录归档时刻:本次归档后用户若不再发新消息,后续 tick 不再重复唤醒归档。
414
- const st = { ...(a.ctx.role.state || {}), lastArchiveAt: Date.now() };
415
- await persona.saveRoleField(a.ctx.role.roleId, 'state', st);
425
+ await persona.updateRoleState(a.ctx.role.roleId,state=>({...state,lastArchiveAt:Date.now()}));
416
426
  log?.info?.('pygmalion heartbeat: archive %s (%s, idle %dmin)', a.ctx.role.roleId, a.date, a.idleMin);
417
427
  } catch (e) { log?.warn?.('pygmalion heartbeat archive %s failed: %o', a.ctx.role.roleId, e); }
418
428
  }
419
429
  // 表情包自动维护:识别待归类 + 周期收集(插件驱动 subagent,导演不参与)。
420
- await memeTick(ctxs);
430
+ // 复用既有角色任务,不让慢收集占住心跳;至多两个在途任务,无持久任务队列。
431
+ for (const ctx of ctxs) {
432
+ const id=ctx.role.roleId;
433
+ if(memeJobs.has(id)||memeJobs.size>=2)continue;
434
+ const job=memeTick([ctx]).finally(()=>memeJobs.delete(id));memeJobs.set(id,job);
435
+ void job.catch(error=>log?.warn?.('表情包维护失败: %o',error));
436
+ }
421
437
  }
422
438
 
439
+ function runOnce() {
440
+ if (running) return running;
441
+ running = tick().finally(() => { running = null; });
442
+ return running;
443
+ }
423
444
  return {
424
445
  start() {
425
446
  if (timer !== null) return;
@@ -431,7 +452,7 @@ export function createHeartbeatScheduler(deps) {
431
452
  timer = setInterval(() => { void runOnce().catch((e) => log?.warn?.('pygmalion heartbeat tick error: %o', e)); }, interval);
432
453
  },
433
454
  stop() {
434
- stopped = true;
455
+ stopped = true; lifetime.abort(new Error('心跳已停止'));
435
456
  if (timer !== null) { clearInterval(timer); timer = null; }
436
457
  },
437
458
  runOnce,