pygmalion 0.1.5 → 0.1.6
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/package.json +1 -1
- package/preset/pygmalion-director/agent.cordis.yml +161 -161
- package/src/active-session.js +25 -2
- package/src/bot-factory.js +282 -282
- package/src/heartbeat.js +352 -352
- package/src/inbound.js +770 -770
- package/src/index.js +210 -210
- package/src/persona.js +380 -380
- package/src/tools.js +511 -511
- package/src/wakeup.js +208 -208
- package/src/web-public/app.js +381 -381
- package/src/web-public/index.html +130 -130
- package/src/web-public/style.css +44 -44
- package/src/web-server.js +506 -506
package/src/heartbeat.js
CHANGED
|
@@ -1,352 +1,352 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Pygmalion 内置心跳:自动对每个「bot 管线服务的角色」执行
|
|
3
|
-
* ① 主动唤醒(角色日程 / 今日未联系问候)
|
|
4
|
-
* ② 沉默归档(用户连续 N 分钟未发言 → 唤醒 dsh 把原始记录切片归档为三层记忆)
|
|
5
|
-
* ③ 非零性检查(角色必须有生活脚本在运行;无脚本在跑 → 节流唤醒 dsh 创作并启动)
|
|
6
|
-
* ④ rewake 到期(director_send reawake 等待队列)
|
|
7
|
-
* 由插件常驻调度器运行(全局唯一,遍历各 bot 管线;数据读写角色 state.json)。
|
|
8
|
-
*/
|
|
9
|
-
import { join } from 'node:path';
|
|
10
|
-
import { readFile, readdir } from 'node:fs/promises';
|
|
11
|
-
import { listRunningLifeScripts, recoverLifeScripts, pruneDeadLifeScripts } from './agent-life.js';
|
|
12
|
-
import { wakeupSession, archiveWakeup } from './wakeup.js';
|
|
13
|
-
import { activeSessionFile } from './active-session.js';
|
|
14
|
-
import { refreshRawRecordFromSession } from './memory-write.js';
|
|
15
|
-
import { inQuietHours } from './quiet-hours.js';
|
|
16
|
-
|
|
17
|
-
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
|
|
18
|
-
|
|
19
|
-
function pad(n) { return String(n).padStart(2, '0'); }
|
|
20
|
-
function nowHm(d = new Date()) { return `${pad(d.getHours())}:${pad(d.getMinutes())}`; }
|
|
21
|
-
function today(d = new Date()) { return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`; }
|
|
22
|
-
function localDateOf(ms) { const d = new Date(ms); return today(d); }
|
|
23
|
-
function minutesAgo(hhmm, now = new Date()) {
|
|
24
|
-
const [h, m] = String(hhmm).split(':').map((x) => Number(x));
|
|
25
|
-
if (!Number.isFinite(h) || !Number.isFinite(m)) return undefined;
|
|
26
|
-
return ((now.getHours() * 60 + now.getMinutes()) - (h * 60 + m));
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
/**
|
|
30
|
-
* @param deps {
|
|
31
|
-
* config, log,
|
|
32
|
-
* persona, // persona lib(loadRole/listRoles/saveRoleField/roleWorkspace/roleDir/dataRoot)
|
|
33
|
-
* pipelines, // per-bot 管线 facade 数组(见 index.js):
|
|
34
|
-
* // { botId, roleId, routes, threads, inbound, withinChatWindowMs, httpApiToken }
|
|
35
|
-
* dshHome // 可选:DSH_HOME 覆盖(测试用)
|
|
36
|
-
* }
|
|
37
|
-
*/
|
|
38
|
-
export function createHeartbeatScheduler(deps) {
|
|
39
|
-
const { config, log, persona, dshHome } = deps;
|
|
40
|
-
// 每次 tick 现取管线列表(数组或访问器均可):网页动态增删 bot 即时生效。
|
|
41
|
-
const currentPipelines = () => (typeof deps.pipelines === 'function' ? deps.pipelines() : deps.pipelines);
|
|
42
|
-
let timer = null;
|
|
43
|
-
let stopped = false;
|
|
44
|
-
// 每个 dsh 进程启动后首个心跳 tick 视为「重启后首次」,无视 lastLifeWarnAt 旧节流:
|
|
45
|
-
// 否则重启前设下的节流会跨重启压制非零性提示(例:重启前刚唤醒过 → 重启后要等整个
|
|
46
|
-
// 窗口才再通知,dsh 一直不知道脚本已经没了)。
|
|
47
|
-
let freshLife = true;
|
|
48
|
-
|
|
49
|
-
/** 每个 bot 管线构建 wakeupSession 依赖(含该管线的 botId/roleId/线程/路由/活动时间/生活脚本状态)。 */
|
|
50
|
-
function wakeBaseFor(p) {
|
|
51
|
-
return {
|
|
52
|
-
threads: p.threads,
|
|
53
|
-
routes: p.routes,
|
|
54
|
-
ensureAgent: (sid) => p.inbound.ensureAgent(sid),
|
|
55
|
-
persona,
|
|
56
|
-
botId: p.botId,
|
|
57
|
-
roleId: p.roleId,
|
|
58
|
-
withinChatWindowMs: p.withinChatWindowMs,
|
|
59
|
-
log,
|
|
60
|
-
activityAt: (sid) => p.inbound.userActivityAt(sid),
|
|
61
|
-
// 是否有生活脚本在运行(非零性判定:有脚本在跑才满足,文件存在不算)。
|
|
62
|
-
// 先恢复 dsh 重启前的运行表,再判非零,避免重启后误判「无脚本在跑」。
|
|
63
|
-
lifeActive: async (ws) => {
|
|
64
|
-
await recoverLifeScripts(ws);
|
|
65
|
-
await pruneDeadLifeScripts(ws);
|
|
66
|
-
return (await listRunningLifeScripts(ws)).length > 0;
|
|
67
|
-
},
|
|
68
|
-
};
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
function archiveBaseFor(p) {
|
|
72
|
-
return {
|
|
73
|
-
threads: p.threads,
|
|
74
|
-
ensureAgent: (sid) => p.inbound.ensureAgent(sid),
|
|
75
|
-
persona,
|
|
76
|
-
botId: p.botId,
|
|
77
|
-
roleId: p.roleId,
|
|
78
|
-
log,
|
|
79
|
-
};
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
/** 收集「有绑定 openid、该 bot 管线服务的角色」上下文(无 openid 无法联系则跳过)。 */
|
|
83
|
-
async function roleContexts() {
|
|
84
|
-
const out = [];
|
|
85
|
-
for (const p of currentPipelines()) {
|
|
86
|
-
const role = await persona.loadRole(p.roleId);
|
|
87
|
-
if (!role) {
|
|
88
|
-
log?.warn?.('pygmalion heartbeat: role %s missing (pipeline %s)', p.roleId, p.botId);
|
|
89
|
-
continue;
|
|
90
|
-
}
|
|
91
|
-
const openid = role.binding?.openid;
|
|
92
|
-
if (!openid) continue;
|
|
93
|
-
out.push({ pipeline: p, role, openid });
|
|
94
|
-
}
|
|
95
|
-
return out;
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
/** 各 c2c openid 的最后用户活动时间(来自该管线路由存储,纯用户消息驱动)。 */
|
|
99
|
-
function lastActivityByOpenid(routes) {
|
|
100
|
-
const map = {};
|
|
101
|
-
for (const { record } of routes.entries()) {
|
|
102
|
-
const t = record?.target;
|
|
103
|
-
if (t?.kind === 'c2c' && t.userId && typeof record.lastMsgAt === 'number')
|
|
104
|
-
map[t.userId] = Math.max(map[t.userId] ?? 0, record.lastMsgAt);
|
|
105
|
-
}
|
|
106
|
-
return map;
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
/** 兜底:每 tick 从活跃会话 session log 提取写日期层原始记录(主触发在 inbound / director_send)。 */
|
|
110
|
-
async function refreshRawRecord({ role, openid, pipeline }) {
|
|
111
|
-
const counter = pipeline.threads?.current(`c2c:${openid}`) ?? 0;
|
|
112
|
-
const file = activeSessionFile({ openid, threadCounter: counter, workspace: role.workspace, dshHome, botId: pipeline.botId });
|
|
113
|
-
const charLabel = role.persona?.name || role.roleId || '角色';
|
|
114
|
-
await refreshRawRecordFromSession({ workspace: role.workspace, sessionFile: file, charLabel, log });
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
/** 收集「需要主动唤醒」的任务。 */
|
|
118
|
-
async function computeWakeups(ctxs, now) {
|
|
119
|
-
const out = [];
|
|
120
|
-
for (const ctx of ctxs) {
|
|
121
|
-
const { role, openid, pipeline } = ctx;
|
|
122
|
-
const pr = role.proactive || {};
|
|
123
|
-
if (pr.enabled === false) continue;
|
|
124
|
-
if (inQuietHours(pr.quietHours || [], now)) continue;
|
|
125
|
-
// 未激活:从没聊过一次的角色不主动唤醒(无用户消息历史 = 未激活)。
|
|
126
|
-
const lastBy = lastActivityByOpenid(pipeline.routes);
|
|
127
|
-
const last = lastBy[openid];
|
|
128
|
-
if (last === undefined) continue;
|
|
129
|
-
const state = role.state || {};
|
|
130
|
-
const todayCount = (state.wakeDates && state.wakeDates[today(now)]) || 0;
|
|
131
|
-
const maxWake = pr.maxWakeupsPerDay ?? 5;
|
|
132
|
-
if (todayCount >= maxWake) continue;
|
|
133
|
-
const schedule = role.persona?.schedule ?? {};
|
|
134
|
-
for (const [k, v] of Object.entries(schedule)) {
|
|
135
|
-
const diff = minutesAgo(String(v), now);
|
|
136
|
-
if (diff !== undefined && Math.abs(diff) <= 3) {
|
|
137
|
-
out.push({ ctx, rule: 'schedule', reason: `按你的日程(${k}=${v})`, memoryHint: `现在是 ${nowHm(now)}`, evening: false });
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
// 「今日未联系」主动问候:以路由存储最后活动时间为准(用户今天还没发过消息)。
|
|
141
|
-
const contactedToday = localDateOf(last) === today(now);
|
|
142
|
-
if (!contactedToday) {
|
|
143
|
-
const diff = minutesAgo(pr.eveningCheck ?? config.heartbeat?.eveningCheck ?? '20:00', now);
|
|
144
|
-
if (diff !== undefined && diff >= 0 && (state.eveningSentDate ?? '') !== today(now)) {
|
|
145
|
-
out.push({ ctx, rule: 'evening', reason: `ta 今天还没有主动找你`, memoryHint: `现在是 ${nowHm(now)},看看记忆里最近聊过什么,像朋友一样自然地开口`, evening: true });
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
return out;
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
/** 收集「需要归档」的任务:用户沉默超时且该日原始记录未主题化。 */
|
|
153
|
-
async function computeArchives(ctxs, now) {
|
|
154
|
-
const ts = Date.now();
|
|
155
|
-
const out = [];
|
|
156
|
-
for (const ctx of ctxs) {
|
|
157
|
-
const { role, openid, pipeline } = ctx;
|
|
158
|
-
const pr = role.proactive || {};
|
|
159
|
-
// 免打扰时段不唤醒 dsh 归档(归档也消耗 dsh 上下文;等安静时段结束后的下一 tick 再处理)。
|
|
160
|
-
if (inQuietHours(pr.quietHours || [], now)) continue;
|
|
161
|
-
const idleLimit = pr.archiveIdleMinutes ?? config.heartbeat?.archiveIdleMinutes ?? 45;
|
|
162
|
-
if (!idleLimit) continue;
|
|
163
|
-
const last = lastActivityByOpenid(pipeline.routes)[openid];
|
|
164
|
-
if (last === undefined) continue;
|
|
165
|
-
// 上次归档后用户没有新消息 → 没有新内容,不重复唤醒 dsh 归档(避免每日空跑)。
|
|
166
|
-
if (typeof role.state?.lastArchiveAt === 'number' && last <= role.state.lastArchiveAt) continue;
|
|
167
|
-
const idleMin = Math.round((ts - last) / 60_000);
|
|
168
|
-
if (idleMin < idleLimit) continue;
|
|
169
|
-
const memDir = join(role.workspace, 'memory');
|
|
170
|
-
let dates = [];
|
|
171
|
-
try { dates = (await readdir(memDir)).filter((n) => DATE_RE.test(n)).sort(); } catch { dates = []; }
|
|
172
|
-
for (const d of dates.slice().reverse()) {
|
|
173
|
-
const hasRaw = await readFile(join(memDir, d, '原始记录.md'), 'utf8').then(() => true).catch(() => false);
|
|
174
|
-
if (!hasRaw) continue;
|
|
175
|
-
const needs = await readFile(join(memDir, d, '索引.md'), 'utf8')
|
|
176
|
-
.then((t) => /(归档日期:|主题化|基础统计|待归档)/.test(t)).catch(() => true);
|
|
177
|
-
if (needs) { out.push({ ctx, date: d, idleMin }); break; }
|
|
178
|
-
}
|
|
179
|
-
}
|
|
180
|
-
return out;
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
/** 记一次主动唤醒(写角色 state.json.wakeDates/eveningSentDate)。 */
|
|
184
|
-
async function bumpState(ctx, { evening = false }) {
|
|
185
|
-
try {
|
|
186
|
-
const state = { ...(ctx.role.state || {}) };
|
|
187
|
-
const key = today();
|
|
188
|
-
state.lastWakeupAt = new Date().toISOString();
|
|
189
|
-
state.wakeDates = { ...(state.wakeDates || {}), [key]: ((state.wakeDates || {})[key] || 0) + 1 };
|
|
190
|
-
if (evening) state.eveningSentDate = key;
|
|
191
|
-
await persona.saveRoleField(ctx.role.roleId, 'state', state);
|
|
192
|
-
} catch (e) { log?.warn?.('heartbeat state write failed: %o', e); }
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
/** ④ 等待脚本(rewake)到期处理:到期且用户这期间没回过 → 唤醒 dsh 继续。 */
|
|
196
|
-
async function rewakeTick(ctxs, now) {
|
|
197
|
-
const ts = now.getTime();
|
|
198
|
-
for (const ctx of ctxs) {
|
|
199
|
-
const { role, openid, pipeline } = ctx;
|
|
200
|
-
const state = { ...(role.state || {}) };
|
|
201
|
-
if (!Array.isArray(state.rewake) || !state.rewake.length) continue;
|
|
202
|
-
const due = state.rewake.filter((r) => r.atMs <= ts);
|
|
203
|
-
if (!due.length) continue;
|
|
204
|
-
const lastBy = lastActivityByOpenid(pipeline.routes);
|
|
205
|
-
for (const r of due) {
|
|
206
|
-
const last = lastBy[openid];
|
|
207
|
-
// 取消语义:从「安排时刻 createdAt」起,用户只要发过任何消息(哪怕在到点之前),
|
|
208
|
-
// 这次等待就自然完成——不再唤醒,节省一次无效调用。
|
|
209
|
-
const bound = r.createdAt ?? r.atMs;
|
|
210
|
-
if (last !== undefined && last >= bound) {
|
|
211
|
-
log?.info?.('pygmalion rewake cancelled for role %s (user replied during wait)', role.roleId);
|
|
212
|
-
state.rewake = state.rewake.filter((x) => x !== r);
|
|
213
|
-
continue;
|
|
214
|
-
}
|
|
215
|
-
// 免打扰时段:rewake 到期也不立即唤醒,留在队列等安静时段结束后的下一 tick 再发。
|
|
216
|
-
if (inQuietHours(role.proactive?.quietHours || [], now)) continue;
|
|
217
|
-
try {
|
|
218
|
-
await wakeupSession(wakeBaseFor(pipeline), {
|
|
219
|
-
target: { kind: 'c2c', userId: openid },
|
|
220
|
-
reason: '等待脚本到期',
|
|
221
|
-
memoryHint: `你之前约定到这个点时回来看看 ta:${r.reason}(ta 这段时间没发消息)`,
|
|
222
|
-
});
|
|
223
|
-
log?.info?.('pygmalion heartbeat: rewake due for role %s', role.roleId);
|
|
224
|
-
} catch (e) { log?.warn?.('pygmalion rewake %s failed: %o', role.roleId, e); }
|
|
225
|
-
state.rewake = state.rewake.filter((x) => x !== r);
|
|
226
|
-
}
|
|
227
|
-
try { await persona.saveRoleField(role.roleId, 'state', state); } catch { /* ignore */ }
|
|
228
|
-
}
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
/**
|
|
232
|
-
* ③ 非零性检查:每个绑定 openid 的角色必须「至少有一个生活脚本在运行」。
|
|
233
|
-
* 有脚本在跑 → 角色生活正常,不打搅 dsh;没有任何脚本在运行(非零性破坏)→
|
|
234
|
-
* 节流(warnIntervalMs)后唤醒 dsh,让它创作角色生活经历并程序化为脚本(life_run 启动)。
|
|
235
|
-
* 插件不限制脚本运行时长/次数;「非零」由 dsh 保证。撞车/静默由 wakeupSession 处理。
|
|
236
|
-
*/
|
|
237
|
-
async function lifeTick(ctxs, now) {
|
|
238
|
-
if (config.heartbeat?.lifeEnabled === false) return;
|
|
239
|
-
const ts = now.getTime();
|
|
240
|
-
const warnIntervalMs = config.heartbeat?.lifeIntervalMs ?? 3 * 3600 * 1000;
|
|
241
|
-
for (const ctx of ctxs) {
|
|
242
|
-
const { role, openid, pipeline } = ctx;
|
|
243
|
-
const pr = role.proactive || {};
|
|
244
|
-
if (pr.lifeEnabled === false) continue;
|
|
245
|
-
// 免打扰时段不唤醒(非零性提醒也等安静时段结束)。
|
|
246
|
-
if (inQuietHours(pr.quietHours || [], now)) continue;
|
|
247
|
-
// 未激活:从没聊过一次的角色不检查(无用户消息历史 = 未激活)。
|
|
248
|
-
if (lastActivityByOpenid(pipeline.routes)[openid] === undefined) continue;
|
|
249
|
-
await recoverLifeScripts(role.workspace);
|
|
250
|
-
await pruneDeadLifeScripts(role.workspace);
|
|
251
|
-
const running = await listRunningLifeScripts(role.workspace);
|
|
252
|
-
if (running.length > 0) continue; // 有脚本在跑 = 非零满足,不打搅 dsh
|
|
253
|
-
const state = { ...(role.state || {}) };
|
|
254
|
-
if (!freshLife && ts - (state.lastLifeWarnAt ?? 0) < warnIntervalMs) continue; // 节流,防每 tick 轰炸
|
|
255
|
-
try {
|
|
256
|
-
const r = await wakeupSession(wakeBaseFor(pipeline), {
|
|
257
|
-
target: { kind: 'c2c', userId: openid },
|
|
258
|
-
reason: '生活脚本未在运行(非零性破坏)',
|
|
259
|
-
kind: 'life',
|
|
260
|
-
});
|
|
261
|
-
if (r?.ok === true) {
|
|
262
|
-
state.lastLifeWarnAt = ts;
|
|
263
|
-
await persona.saveRoleField(role.roleId, 'state', state);
|
|
264
|
-
log?.info?.('pygmalion heartbeat: life nonzero warn %s (no script running)', role.roleId);
|
|
265
|
-
}
|
|
266
|
-
} catch (e) { log?.warn?.('pygmalion heartbeat life %s failed: %o', role.roleId, e); }
|
|
267
|
-
}
|
|
268
|
-
// 首个 tick 已执行(无论是否唤醒),之后恢复节流。
|
|
269
|
-
freshLife = false;
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
/**
|
|
273
|
-
* ⑤ 免打扰时段推迟的唤醒:脚本在安静时段调用 /wakeup 时,插件把唤醒写入
|
|
274
|
-
* role.state.deferredWakeup(合并:多次唤醒只留最新一次),不丢弃;这里在
|
|
275
|
-
* 安静时段结束后把它真正唤醒 dsh。
|
|
276
|
-
*/
|
|
277
|
-
async function deferredWakeupTick(ctxs, now) {
|
|
278
|
-
for (const ctx of ctxs) {
|
|
279
|
-
const { role, openid, pipeline } = ctx;
|
|
280
|
-
const state = role.state || {};
|
|
281
|
-
if (!state.deferredWakeup) continue;
|
|
282
|
-
if (inQuietHours(role.proactive?.quietHours || [], now)) continue; // 仍在安静时段,继续等
|
|
283
|
-
const dw = state.deferredWakeup;
|
|
284
|
-
try {
|
|
285
|
-
const r = await wakeupSession(wakeBaseFor(pipeline), {
|
|
286
|
-
target: { kind: 'c2c', userId: openid },
|
|
287
|
-
reason: dw.reason || '免打扰时段推迟的脚本唤醒',
|
|
288
|
-
memoryHint: dw.memoryHint,
|
|
289
|
-
kind: dw.kind,
|
|
290
|
-
mood: dw.mood,
|
|
291
|
-
topic: dw.topic,
|
|
292
|
-
force: dw.force,
|
|
293
|
-
});
|
|
294
|
-
log?.info?.('pygmalion heartbeat: deferred wakeup fired %s (ok=%s)', role.roleId, Boolean(r?.ok));
|
|
295
|
-
} catch (e) { log?.warn?.('pygmalion deferred wakeup %s failed: %o', role.roleId, e); }
|
|
296
|
-
const st = { ...state, deferredWakeup: undefined };
|
|
297
|
-
if (dw.kind === 'script-hook') st.lastScriptWakeAt = Date.now();
|
|
298
|
-
try { await persona.saveRoleField(role.roleId, 'state', st); } catch { /* ignore */ }
|
|
299
|
-
}
|
|
300
|
-
}
|
|
301
|
-
|
|
302
|
-
async function runOnce() {
|
|
303
|
-
if (stopped) return;
|
|
304
|
-
const ctxs = await roleContexts();
|
|
305
|
-
const now = new Date();
|
|
306
|
-
// 兜底:从活跃会话 session log 提取写日期层原始记录(主触发在 inbound / director_send)
|
|
307
|
-
for (const ctx of ctxs) {
|
|
308
|
-
try { await refreshRawRecord(ctx); }
|
|
309
|
-
catch (e) { log?.warn?.('pygmalion raw record %s failed: %o', ctx.role.roleId, e); }
|
|
310
|
-
}
|
|
311
|
-
for (const w of await computeWakeups(ctxs, now)) {
|
|
312
|
-
try {
|
|
313
|
-
const r = await wakeupSession(wakeBaseFor(w.ctx.pipeline), {
|
|
314
|
-
target: { kind: 'c2c', userId: w.ctx.openid },
|
|
315
|
-
reason: w.reason,
|
|
316
|
-
memoryHint: w.memoryHint,
|
|
317
|
-
});
|
|
318
|
-
if (r?.ok) await bumpState(w.ctx, { evening: w.evening });
|
|
319
|
-
log?.info?.('pygmalion heartbeat: wakeup %s (%s) ok=%s', w.ctx.role.roleId, w.rule, Boolean(r?.ok));
|
|
320
|
-
} catch (e) { log?.warn?.('pygmalion heartbeat wakeup %s failed: %o', w.ctx.role.roleId, e); }
|
|
321
|
-
}
|
|
322
|
-
await lifeTick(ctxs, now);
|
|
323
|
-
await rewakeTick(ctxs, now);
|
|
324
|
-
await deferredWakeupTick(ctxs, now);
|
|
325
|
-
for (const a of await computeArchives(ctxs, now)) {
|
|
326
|
-
try {
|
|
327
|
-
await archiveWakeup(archiveBaseFor(a.ctx.pipeline), { target: { kind: 'c2c', userId: a.ctx.openid }, date: a.date });
|
|
328
|
-
// 记录归档时刻:本次归档后用户若不再发新消息,后续 tick 不再重复唤醒归档。
|
|
329
|
-
const st = { ...(a.ctx.role.state || {}), lastArchiveAt: Date.now() };
|
|
330
|
-
await persona.saveRoleField(a.ctx.role.roleId, 'state', st);
|
|
331
|
-
log?.info?.('pygmalion heartbeat: archive %s (%s, idle %dmin)', a.ctx.role.roleId, a.date, a.idleMin);
|
|
332
|
-
} catch (e) { log?.warn?.('pygmalion heartbeat archive %s failed: %o', a.ctx.role.roleId, e); }
|
|
333
|
-
}
|
|
334
|
-
}
|
|
335
|
-
|
|
336
|
-
return {
|
|
337
|
-
start() {
|
|
338
|
-
if (timer !== null) return;
|
|
339
|
-
if (config.heartbeat?.enabled === false) { log?.info?.('pygmalion heartbeat disabled by config'); return; }
|
|
340
|
-
freshLife = true; // 本次进程运行期首个 tick 无视旧节流(重启后立刻查一次非零)
|
|
341
|
-
const interval = Math.max(Number(config.heartbeat?.intervalMs) || 60_000, 5_000);
|
|
342
|
-
log?.info?.('pygmalion heartbeat started (interval=%dms, archiveIdle=%dmin, pipelines=%d)', interval, config.heartbeat?.archiveIdleMinutes ?? 45, currentPipelines().length);
|
|
343
|
-
setTimeout(() => { void runOnce(); }, 3_000);
|
|
344
|
-
timer = setInterval(() => { void runOnce().catch((e) => log?.warn?.('pygmalion heartbeat tick error: %o', e)); }, interval);
|
|
345
|
-
},
|
|
346
|
-
stop() {
|
|
347
|
-
stopped = true;
|
|
348
|
-
if (timer !== null) { clearInterval(timer); timer = null; }
|
|
349
|
-
},
|
|
350
|
-
runOnce,
|
|
351
|
-
};
|
|
352
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* Pygmalion 内置心跳:自动对每个「bot 管线服务的角色」执行
|
|
3
|
+
* ① 主动唤醒(角色日程 / 今日未联系问候)
|
|
4
|
+
* ② 沉默归档(用户连续 N 分钟未发言 → 唤醒 dsh 把原始记录切片归档为三层记忆)
|
|
5
|
+
* ③ 非零性检查(角色必须有生活脚本在运行;无脚本在跑 → 节流唤醒 dsh 创作并启动)
|
|
6
|
+
* ④ rewake 到期(director_send reawake 等待队列)
|
|
7
|
+
* 由插件常驻调度器运行(全局唯一,遍历各 bot 管线;数据读写角色 state.json)。
|
|
8
|
+
*/
|
|
9
|
+
import { join } from 'node:path';
|
|
10
|
+
import { readFile, readdir } from 'node:fs/promises';
|
|
11
|
+
import { listRunningLifeScripts, recoverLifeScripts, pruneDeadLifeScripts } from './agent-life.js';
|
|
12
|
+
import { wakeupSession, archiveWakeup } from './wakeup.js';
|
|
13
|
+
import { activeSessionFile } from './active-session.js';
|
|
14
|
+
import { refreshRawRecordFromSession } from './memory-write.js';
|
|
15
|
+
import { inQuietHours } from './quiet-hours.js';
|
|
16
|
+
|
|
17
|
+
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
|
|
18
|
+
|
|
19
|
+
function pad(n) { return String(n).padStart(2, '0'); }
|
|
20
|
+
function nowHm(d = new Date()) { return `${pad(d.getHours())}:${pad(d.getMinutes())}`; }
|
|
21
|
+
function today(d = new Date()) { return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`; }
|
|
22
|
+
function localDateOf(ms) { const d = new Date(ms); return today(d); }
|
|
23
|
+
function minutesAgo(hhmm, now = new Date()) {
|
|
24
|
+
const [h, m] = String(hhmm).split(':').map((x) => Number(x));
|
|
25
|
+
if (!Number.isFinite(h) || !Number.isFinite(m)) return undefined;
|
|
26
|
+
return ((now.getHours() * 60 + now.getMinutes()) - (h * 60 + m));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* @param deps {
|
|
31
|
+
* config, log,
|
|
32
|
+
* persona, // persona lib(loadRole/listRoles/saveRoleField/roleWorkspace/roleDir/dataRoot)
|
|
33
|
+
* pipelines, // per-bot 管线 facade 数组(见 index.js):
|
|
34
|
+
* // { botId, roleId, routes, threads, inbound, withinChatWindowMs, httpApiToken }
|
|
35
|
+
* dshHome // 可选:DSH_HOME 覆盖(测试用)
|
|
36
|
+
* }
|
|
37
|
+
*/
|
|
38
|
+
export function createHeartbeatScheduler(deps) {
|
|
39
|
+
const { config, log, persona, dshHome } = deps;
|
|
40
|
+
// 每次 tick 现取管线列表(数组或访问器均可):网页动态增删 bot 即时生效。
|
|
41
|
+
const currentPipelines = () => (typeof deps.pipelines === 'function' ? deps.pipelines() : deps.pipelines);
|
|
42
|
+
let timer = null;
|
|
43
|
+
let stopped = false;
|
|
44
|
+
// 每个 dsh 进程启动后首个心跳 tick 视为「重启后首次」,无视 lastLifeWarnAt 旧节流:
|
|
45
|
+
// 否则重启前设下的节流会跨重启压制非零性提示(例:重启前刚唤醒过 → 重启后要等整个
|
|
46
|
+
// 窗口才再通知,dsh 一直不知道脚本已经没了)。
|
|
47
|
+
let freshLife = true;
|
|
48
|
+
|
|
49
|
+
/** 每个 bot 管线构建 wakeupSession 依赖(含该管线的 botId/roleId/线程/路由/活动时间/生活脚本状态)。 */
|
|
50
|
+
function wakeBaseFor(p) {
|
|
51
|
+
return {
|
|
52
|
+
threads: p.threads,
|
|
53
|
+
routes: p.routes,
|
|
54
|
+
ensureAgent: (sid) => p.inbound.ensureAgent(sid),
|
|
55
|
+
persona,
|
|
56
|
+
botId: p.botId,
|
|
57
|
+
roleId: p.roleId,
|
|
58
|
+
withinChatWindowMs: p.withinChatWindowMs,
|
|
59
|
+
log,
|
|
60
|
+
activityAt: (sid) => p.inbound.userActivityAt(sid),
|
|
61
|
+
// 是否有生活脚本在运行(非零性判定:有脚本在跑才满足,文件存在不算)。
|
|
62
|
+
// 先恢复 dsh 重启前的运行表,再判非零,避免重启后误判「无脚本在跑」。
|
|
63
|
+
lifeActive: async (ws) => {
|
|
64
|
+
await recoverLifeScripts(ws);
|
|
65
|
+
await pruneDeadLifeScripts(ws);
|
|
66
|
+
return (await listRunningLifeScripts(ws)).length > 0;
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function archiveBaseFor(p) {
|
|
72
|
+
return {
|
|
73
|
+
threads: p.threads,
|
|
74
|
+
ensureAgent: (sid) => p.inbound.ensureAgent(sid),
|
|
75
|
+
persona,
|
|
76
|
+
botId: p.botId,
|
|
77
|
+
roleId: p.roleId,
|
|
78
|
+
log,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** 收集「有绑定 openid、该 bot 管线服务的角色」上下文(无 openid 无法联系则跳过)。 */
|
|
83
|
+
async function roleContexts() {
|
|
84
|
+
const out = [];
|
|
85
|
+
for (const p of currentPipelines()) {
|
|
86
|
+
const role = await persona.loadRole(p.roleId);
|
|
87
|
+
if (!role) {
|
|
88
|
+
log?.warn?.('pygmalion heartbeat: role %s missing (pipeline %s)', p.roleId, p.botId);
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
const openid = role.binding?.openid;
|
|
92
|
+
if (!openid) continue;
|
|
93
|
+
out.push({ pipeline: p, role, openid });
|
|
94
|
+
}
|
|
95
|
+
return out;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** 各 c2c openid 的最后用户活动时间(来自该管线路由存储,纯用户消息驱动)。 */
|
|
99
|
+
function lastActivityByOpenid(routes) {
|
|
100
|
+
const map = {};
|
|
101
|
+
for (const { record } of routes.entries()) {
|
|
102
|
+
const t = record?.target;
|
|
103
|
+
if (t?.kind === 'c2c' && t.userId && typeof record.lastMsgAt === 'number')
|
|
104
|
+
map[t.userId] = Math.max(map[t.userId] ?? 0, record.lastMsgAt);
|
|
105
|
+
}
|
|
106
|
+
return map;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** 兜底:每 tick 从活跃会话 session log 提取写日期层原始记录(主触发在 inbound / director_send)。 */
|
|
110
|
+
async function refreshRawRecord({ role, openid, pipeline }) {
|
|
111
|
+
const counter = pipeline.threads?.current(`c2c:${openid}`) ?? 0;
|
|
112
|
+
const file = activeSessionFile({ openid, threadCounter: counter, workspace: role.workspace, dshHome, botId: pipeline.botId });
|
|
113
|
+
const charLabel = role.persona?.name || role.roleId || '角色';
|
|
114
|
+
await refreshRawRecordFromSession({ workspace: role.workspace, sessionFile: file, charLabel, log });
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** 收集「需要主动唤醒」的任务。 */
|
|
118
|
+
async function computeWakeups(ctxs, now) {
|
|
119
|
+
const out = [];
|
|
120
|
+
for (const ctx of ctxs) {
|
|
121
|
+
const { role, openid, pipeline } = ctx;
|
|
122
|
+
const pr = role.proactive || {};
|
|
123
|
+
if (pr.enabled === false) continue;
|
|
124
|
+
if (inQuietHours(pr.quietHours || [], now)) continue;
|
|
125
|
+
// 未激活:从没聊过一次的角色不主动唤醒(无用户消息历史 = 未激活)。
|
|
126
|
+
const lastBy = lastActivityByOpenid(pipeline.routes);
|
|
127
|
+
const last = lastBy[openid];
|
|
128
|
+
if (last === undefined) continue;
|
|
129
|
+
const state = role.state || {};
|
|
130
|
+
const todayCount = (state.wakeDates && state.wakeDates[today(now)]) || 0;
|
|
131
|
+
const maxWake = pr.maxWakeupsPerDay ?? 5;
|
|
132
|
+
if (todayCount >= maxWake) continue;
|
|
133
|
+
const schedule = role.persona?.schedule ?? {};
|
|
134
|
+
for (const [k, v] of Object.entries(schedule)) {
|
|
135
|
+
const diff = minutesAgo(String(v), now);
|
|
136
|
+
if (diff !== undefined && Math.abs(diff) <= 3) {
|
|
137
|
+
out.push({ ctx, rule: 'schedule', reason: `按你的日程(${k}=${v})`, memoryHint: `现在是 ${nowHm(now)}`, evening: false });
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
// 「今日未联系」主动问候:以路由存储最后活动时间为准(用户今天还没发过消息)。
|
|
141
|
+
const contactedToday = localDateOf(last) === today(now);
|
|
142
|
+
if (!contactedToday) {
|
|
143
|
+
const diff = minutesAgo(pr.eveningCheck ?? config.heartbeat?.eveningCheck ?? '20:00', now);
|
|
144
|
+
if (diff !== undefined && diff >= 0 && (state.eveningSentDate ?? '') !== today(now)) {
|
|
145
|
+
out.push({ ctx, rule: 'evening', reason: `ta 今天还没有主动找你`, memoryHint: `现在是 ${nowHm(now)},看看记忆里最近聊过什么,像朋友一样自然地开口`, evening: true });
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return out;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** 收集「需要归档」的任务:用户沉默超时且该日原始记录未主题化。 */
|
|
153
|
+
async function computeArchives(ctxs, now) {
|
|
154
|
+
const ts = Date.now();
|
|
155
|
+
const out = [];
|
|
156
|
+
for (const ctx of ctxs) {
|
|
157
|
+
const { role, openid, pipeline } = ctx;
|
|
158
|
+
const pr = role.proactive || {};
|
|
159
|
+
// 免打扰时段不唤醒 dsh 归档(归档也消耗 dsh 上下文;等安静时段结束后的下一 tick 再处理)。
|
|
160
|
+
if (inQuietHours(pr.quietHours || [], now)) continue;
|
|
161
|
+
const idleLimit = pr.archiveIdleMinutes ?? config.heartbeat?.archiveIdleMinutes ?? 45;
|
|
162
|
+
if (!idleLimit) continue;
|
|
163
|
+
const last = lastActivityByOpenid(pipeline.routes)[openid];
|
|
164
|
+
if (last === undefined) continue;
|
|
165
|
+
// 上次归档后用户没有新消息 → 没有新内容,不重复唤醒 dsh 归档(避免每日空跑)。
|
|
166
|
+
if (typeof role.state?.lastArchiveAt === 'number' && last <= role.state.lastArchiveAt) continue;
|
|
167
|
+
const idleMin = Math.round((ts - last) / 60_000);
|
|
168
|
+
if (idleMin < idleLimit) continue;
|
|
169
|
+
const memDir = join(role.workspace, 'memory');
|
|
170
|
+
let dates = [];
|
|
171
|
+
try { dates = (await readdir(memDir)).filter((n) => DATE_RE.test(n)).sort(); } catch { dates = []; }
|
|
172
|
+
for (const d of dates.slice().reverse()) {
|
|
173
|
+
const hasRaw = await readFile(join(memDir, d, '原始记录.md'), 'utf8').then(() => true).catch(() => false);
|
|
174
|
+
if (!hasRaw) continue;
|
|
175
|
+
const needs = await readFile(join(memDir, d, '索引.md'), 'utf8')
|
|
176
|
+
.then((t) => /(归档日期:|主题化|基础统计|待归档)/.test(t)).catch(() => true);
|
|
177
|
+
if (needs) { out.push({ ctx, date: d, idleMin }); break; }
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
return out;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** 记一次主动唤醒(写角色 state.json.wakeDates/eveningSentDate)。 */
|
|
184
|
+
async function bumpState(ctx, { evening = false }) {
|
|
185
|
+
try {
|
|
186
|
+
const state = { ...(ctx.role.state || {}) };
|
|
187
|
+
const key = today();
|
|
188
|
+
state.lastWakeupAt = new Date().toISOString();
|
|
189
|
+
state.wakeDates = { ...(state.wakeDates || {}), [key]: ((state.wakeDates || {})[key] || 0) + 1 };
|
|
190
|
+
if (evening) state.eveningSentDate = key;
|
|
191
|
+
await persona.saveRoleField(ctx.role.roleId, 'state', state);
|
|
192
|
+
} catch (e) { log?.warn?.('heartbeat state write failed: %o', e); }
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** ④ 等待脚本(rewake)到期处理:到期且用户这期间没回过 → 唤醒 dsh 继续。 */
|
|
196
|
+
async function rewakeTick(ctxs, now) {
|
|
197
|
+
const ts = now.getTime();
|
|
198
|
+
for (const ctx of ctxs) {
|
|
199
|
+
const { role, openid, pipeline } = ctx;
|
|
200
|
+
const state = { ...(role.state || {}) };
|
|
201
|
+
if (!Array.isArray(state.rewake) || !state.rewake.length) continue;
|
|
202
|
+
const due = state.rewake.filter((r) => r.atMs <= ts);
|
|
203
|
+
if (!due.length) continue;
|
|
204
|
+
const lastBy = lastActivityByOpenid(pipeline.routes);
|
|
205
|
+
for (const r of due) {
|
|
206
|
+
const last = lastBy[openid];
|
|
207
|
+
// 取消语义:从「安排时刻 createdAt」起,用户只要发过任何消息(哪怕在到点之前),
|
|
208
|
+
// 这次等待就自然完成——不再唤醒,节省一次无效调用。
|
|
209
|
+
const bound = r.createdAt ?? r.atMs;
|
|
210
|
+
if (last !== undefined && last >= bound) {
|
|
211
|
+
log?.info?.('pygmalion rewake cancelled for role %s (user replied during wait)', role.roleId);
|
|
212
|
+
state.rewake = state.rewake.filter((x) => x !== r);
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
// 免打扰时段:rewake 到期也不立即唤醒,留在队列等安静时段结束后的下一 tick 再发。
|
|
216
|
+
if (inQuietHours(role.proactive?.quietHours || [], now)) continue;
|
|
217
|
+
try {
|
|
218
|
+
await wakeupSession(wakeBaseFor(pipeline), {
|
|
219
|
+
target: { kind: 'c2c', userId: openid },
|
|
220
|
+
reason: '等待脚本到期',
|
|
221
|
+
memoryHint: `你之前约定到这个点时回来看看 ta:${r.reason}(ta 这段时间没发消息)`,
|
|
222
|
+
});
|
|
223
|
+
log?.info?.('pygmalion heartbeat: rewake due for role %s', role.roleId);
|
|
224
|
+
} catch (e) { log?.warn?.('pygmalion rewake %s failed: %o', role.roleId, e); }
|
|
225
|
+
state.rewake = state.rewake.filter((x) => x !== r);
|
|
226
|
+
}
|
|
227
|
+
try { await persona.saveRoleField(role.roleId, 'state', state); } catch { /* ignore */ }
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* ③ 非零性检查:每个绑定 openid 的角色必须「至少有一个生活脚本在运行」。
|
|
233
|
+
* 有脚本在跑 → 角色生活正常,不打搅 dsh;没有任何脚本在运行(非零性破坏)→
|
|
234
|
+
* 节流(warnIntervalMs)后唤醒 dsh,让它创作角色生活经历并程序化为脚本(life_run 启动)。
|
|
235
|
+
* 插件不限制脚本运行时长/次数;「非零」由 dsh 保证。撞车/静默由 wakeupSession 处理。
|
|
236
|
+
*/
|
|
237
|
+
async function lifeTick(ctxs, now) {
|
|
238
|
+
if (config.heartbeat?.lifeEnabled === false) return;
|
|
239
|
+
const ts = now.getTime();
|
|
240
|
+
const warnIntervalMs = config.heartbeat?.lifeIntervalMs ?? 3 * 3600 * 1000;
|
|
241
|
+
for (const ctx of ctxs) {
|
|
242
|
+
const { role, openid, pipeline } = ctx;
|
|
243
|
+
const pr = role.proactive || {};
|
|
244
|
+
if (pr.lifeEnabled === false) continue;
|
|
245
|
+
// 免打扰时段不唤醒(非零性提醒也等安静时段结束)。
|
|
246
|
+
if (inQuietHours(pr.quietHours || [], now)) continue;
|
|
247
|
+
// 未激活:从没聊过一次的角色不检查(无用户消息历史 = 未激活)。
|
|
248
|
+
if (lastActivityByOpenid(pipeline.routes)[openid] === undefined) continue;
|
|
249
|
+
await recoverLifeScripts(role.workspace);
|
|
250
|
+
await pruneDeadLifeScripts(role.workspace);
|
|
251
|
+
const running = await listRunningLifeScripts(role.workspace);
|
|
252
|
+
if (running.length > 0) continue; // 有脚本在跑 = 非零满足,不打搅 dsh
|
|
253
|
+
const state = { ...(role.state || {}) };
|
|
254
|
+
if (!freshLife && ts - (state.lastLifeWarnAt ?? 0) < warnIntervalMs) continue; // 节流,防每 tick 轰炸
|
|
255
|
+
try {
|
|
256
|
+
const r = await wakeupSession(wakeBaseFor(pipeline), {
|
|
257
|
+
target: { kind: 'c2c', userId: openid },
|
|
258
|
+
reason: '生活脚本未在运行(非零性破坏)',
|
|
259
|
+
kind: 'life',
|
|
260
|
+
});
|
|
261
|
+
if (r?.ok === true) {
|
|
262
|
+
state.lastLifeWarnAt = ts;
|
|
263
|
+
await persona.saveRoleField(role.roleId, 'state', state);
|
|
264
|
+
log?.info?.('pygmalion heartbeat: life nonzero warn %s (no script running)', role.roleId);
|
|
265
|
+
}
|
|
266
|
+
} catch (e) { log?.warn?.('pygmalion heartbeat life %s failed: %o', role.roleId, e); }
|
|
267
|
+
}
|
|
268
|
+
// 首个 tick 已执行(无论是否唤醒),之后恢复节流。
|
|
269
|
+
freshLife = false;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* ⑤ 免打扰时段推迟的唤醒:脚本在安静时段调用 /wakeup 时,插件把唤醒写入
|
|
274
|
+
* role.state.deferredWakeup(合并:多次唤醒只留最新一次),不丢弃;这里在
|
|
275
|
+
* 安静时段结束后把它真正唤醒 dsh。
|
|
276
|
+
*/
|
|
277
|
+
async function deferredWakeupTick(ctxs, now) {
|
|
278
|
+
for (const ctx of ctxs) {
|
|
279
|
+
const { role, openid, pipeline } = ctx;
|
|
280
|
+
const state = role.state || {};
|
|
281
|
+
if (!state.deferredWakeup) continue;
|
|
282
|
+
if (inQuietHours(role.proactive?.quietHours || [], now)) continue; // 仍在安静时段,继续等
|
|
283
|
+
const dw = state.deferredWakeup;
|
|
284
|
+
try {
|
|
285
|
+
const r = await wakeupSession(wakeBaseFor(pipeline), {
|
|
286
|
+
target: { kind: 'c2c', userId: openid },
|
|
287
|
+
reason: dw.reason || '免打扰时段推迟的脚本唤醒',
|
|
288
|
+
memoryHint: dw.memoryHint,
|
|
289
|
+
kind: dw.kind,
|
|
290
|
+
mood: dw.mood,
|
|
291
|
+
topic: dw.topic,
|
|
292
|
+
force: dw.force,
|
|
293
|
+
});
|
|
294
|
+
log?.info?.('pygmalion heartbeat: deferred wakeup fired %s (ok=%s)', role.roleId, Boolean(r?.ok));
|
|
295
|
+
} catch (e) { log?.warn?.('pygmalion deferred wakeup %s failed: %o', role.roleId, e); }
|
|
296
|
+
const st = { ...state, deferredWakeup: undefined };
|
|
297
|
+
if (dw.kind === 'script-hook') st.lastScriptWakeAt = Date.now();
|
|
298
|
+
try { await persona.saveRoleField(role.roleId, 'state', st); } catch { /* ignore */ }
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
async function runOnce() {
|
|
303
|
+
if (stopped) return;
|
|
304
|
+
const ctxs = await roleContexts();
|
|
305
|
+
const now = new Date();
|
|
306
|
+
// 兜底:从活跃会话 session log 提取写日期层原始记录(主触发在 inbound / director_send)
|
|
307
|
+
for (const ctx of ctxs) {
|
|
308
|
+
try { await refreshRawRecord(ctx); }
|
|
309
|
+
catch (e) { log?.warn?.('pygmalion raw record %s failed: %o', ctx.role.roleId, e); }
|
|
310
|
+
}
|
|
311
|
+
for (const w of await computeWakeups(ctxs, now)) {
|
|
312
|
+
try {
|
|
313
|
+
const r = await wakeupSession(wakeBaseFor(w.ctx.pipeline), {
|
|
314
|
+
target: { kind: 'c2c', userId: w.ctx.openid },
|
|
315
|
+
reason: w.reason,
|
|
316
|
+
memoryHint: w.memoryHint,
|
|
317
|
+
});
|
|
318
|
+
if (r?.ok) await bumpState(w.ctx, { evening: w.evening });
|
|
319
|
+
log?.info?.('pygmalion heartbeat: wakeup %s (%s) ok=%s', w.ctx.role.roleId, w.rule, Boolean(r?.ok));
|
|
320
|
+
} catch (e) { log?.warn?.('pygmalion heartbeat wakeup %s failed: %o', w.ctx.role.roleId, e); }
|
|
321
|
+
}
|
|
322
|
+
await lifeTick(ctxs, now);
|
|
323
|
+
await rewakeTick(ctxs, now);
|
|
324
|
+
await deferredWakeupTick(ctxs, now);
|
|
325
|
+
for (const a of await computeArchives(ctxs, now)) {
|
|
326
|
+
try {
|
|
327
|
+
await archiveWakeup(archiveBaseFor(a.ctx.pipeline), { target: { kind: 'c2c', userId: a.ctx.openid }, date: a.date });
|
|
328
|
+
// 记录归档时刻:本次归档后用户若不再发新消息,后续 tick 不再重复唤醒归档。
|
|
329
|
+
const st = { ...(a.ctx.role.state || {}), lastArchiveAt: Date.now() };
|
|
330
|
+
await persona.saveRoleField(a.ctx.role.roleId, 'state', st);
|
|
331
|
+
log?.info?.('pygmalion heartbeat: archive %s (%s, idle %dmin)', a.ctx.role.roleId, a.date, a.idleMin);
|
|
332
|
+
} catch (e) { log?.warn?.('pygmalion heartbeat archive %s failed: %o', a.ctx.role.roleId, e); }
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
return {
|
|
337
|
+
start() {
|
|
338
|
+
if (timer !== null) return;
|
|
339
|
+
if (config.heartbeat?.enabled === false) { log?.info?.('pygmalion heartbeat disabled by config'); return; }
|
|
340
|
+
freshLife = true; // 本次进程运行期首个 tick 无视旧节流(重启后立刻查一次非零)
|
|
341
|
+
const interval = Math.max(Number(config.heartbeat?.intervalMs) || 60_000, 5_000);
|
|
342
|
+
log?.info?.('pygmalion heartbeat started (interval=%dms, archiveIdle=%dmin, pipelines=%d)', interval, config.heartbeat?.archiveIdleMinutes ?? 45, currentPipelines().length);
|
|
343
|
+
setTimeout(() => { void runOnce(); }, 3_000);
|
|
344
|
+
timer = setInterval(() => { void runOnce().catch((e) => log?.warn?.('pygmalion heartbeat tick error: %o', e)); }, interval);
|
|
345
|
+
},
|
|
346
|
+
stop() {
|
|
347
|
+
stopped = true;
|
|
348
|
+
if (timer !== null) { clearInterval(timer); timer = null; }
|
|
349
|
+
},
|
|
350
|
+
runOnce,
|
|
351
|
+
};
|
|
352
|
+
}
|