pygmalion 0.1.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.
@@ -0,0 +1,73 @@
1
+ /**
2
+ * DSH-side bookkeeping: two small helpers that keep QQ sessions visible
3
+ * inside the host application's sidebar / workspace tree. Both functions
4
+ * are best-effort — failures must not crash the plugin.
5
+ *
6
+ * • `unarchiveOwnQQSessions` strips archived entries whose id starts with
7
+ * `qq:` so newly-resumed sessions are not hidden from the sidebar.
8
+ * • `attachSessionToCwdWorkspace` ensures the workspace owning the agent's
9
+ * cwd exists and the session is attached to it, so the session groups
10
+ * under the right project in the sidebar.
11
+ */
12
+ import { readFile, writeFile } from 'node:fs/promises';
13
+ import { join } from 'node:path';
14
+ /** Strip archived QQ sessions from `~/.dsh/storages/workspace.json`. */
15
+ export async function unarchiveOwnQQSessions(home, prefix, log) {
16
+ const path = join(home, 'storages', 'workspace.json');
17
+ let raw;
18
+ try {
19
+ raw = await readFile(path, 'utf8');
20
+ }
21
+ catch {
22
+ return;
23
+ }
24
+ let parsed;
25
+ try {
26
+ parsed = JSON.parse(raw);
27
+ }
28
+ catch (error) {
29
+ if (log.debug !== undefined)
30
+ log.debug('unarchive: workspace.json not JSON (%o)', error);
31
+ return;
32
+ }
33
+ const root = parsed;
34
+ const archived = root.global?.archivedSessionIds;
35
+ if (!Array.isArray(archived) || archived.length === 0)
36
+ return;
37
+ const kept = archived.filter((id) => typeof id === 'string' && !id.startsWith(prefix));
38
+ if (kept.length === archived.length)
39
+ return;
40
+ const next = { ...root, global: { ...root.global, archivedSessionIds: kept } };
41
+ try {
42
+ await writeFile(path, JSON.stringify(next, null, 2));
43
+ }
44
+ catch (error) {
45
+ if (log.debug !== undefined)
46
+ log.debug('unarchive: write failed (%o)', error);
47
+ }
48
+ }
49
+ /** Group the session under the workspace that owns its cwd (sidebar grouping). */
50
+ export async function attachSessionToCwdWorkspace(registry, cwd, sessionId, log) {
51
+ if (registry === undefined)
52
+ return;
53
+ let workspace;
54
+ try {
55
+ workspace = await registry.resolveByPath(cwd);
56
+ if (workspace === undefined)
57
+ workspace = await registry.create(cwd);
58
+ }
59
+ catch (error) {
60
+ if (log.debug !== undefined)
61
+ log.debug('attachSessionToCwdWorkspace: resolve/create failed for %s (%o)', cwd, error);
62
+ return;
63
+ }
64
+ try {
65
+ await workspace.attachSession(sessionId);
66
+ }
67
+ catch (error) {
68
+ // Header/cwd drift: sidebar grouping is skipped, replies are unaffected.
69
+ if (log.debug !== undefined)
70
+ log.debug('attachSessionToCwdWorkspace: attachSession(%s) failed (%o)', sessionId, error);
71
+ }
72
+ }
73
+ //# sourceMappingURL=dsh-bookkeeping.js.map
package/src/gateway.js ADDED
@@ -0,0 +1,248 @@
1
+ /**
2
+ * QQ WebSocket gateway: identify with intents, heartbeat, session RESUME
3
+ * (session_id + seq persisted across restarts), reconnect with backoff, and
4
+ * dispatch op-0 events (messages, interactions, lifecycle) to registered
5
+ * handlers.
6
+ */
7
+ import WebSocket from 'ws';
8
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
9
+ import { dirname } from 'node:path';
10
+ export const INTENT = {
11
+ GUILDS: 1 << 0,
12
+ GUILD_MEMBERS: 1 << 1,
13
+ PUBLIC_GUILD_MESSAGES: 1 << 30,
14
+ DIRECT_MESSAGE: 1 << 12,
15
+ GROUP_AND_C2C: 1 << 25,
16
+ INTERACTION: 1 << 26,
17
+ };
18
+ export const DEFAULT_INTENTS = INTENT.PUBLIC_GUILD_MESSAGES | INTENT.GROUP_AND_C2C;
19
+ const RECONNECT_DELAYS = [1_000, 2_000, 5_000, 10_000, 30_000, 60_000];
20
+ export class QQGateway {
21
+ config;
22
+ api;
23
+ hooks;
24
+ log;
25
+ socket;
26
+ heartbeat;
27
+ reconnectTimer;
28
+ lastSequence = null;
29
+ sessionId;
30
+ resumeAttempted = false;
31
+ reconnectAttempt = 0;
32
+ connecting = false;
33
+ disposed = false;
34
+ sessionFile;
35
+ constructor(config, api, hooks, log, sessionFile) {
36
+ this.config = config;
37
+ this.api = api;
38
+ this.hooks = hooks;
39
+ this.log = log;
40
+ this.sessionFile = sessionFile;
41
+ }
42
+ /** Load persisted session state and start the connection loop. */
43
+ async start() {
44
+ try {
45
+ const raw = await readFile(this.sessionFile, 'utf8');
46
+ const parsed = JSON.parse(raw);
47
+ this.sessionId = typeof parsed.sessionId === 'string' ? parsed.sessionId : undefined;
48
+ this.lastSequence = typeof parsed.seq === 'number' ? parsed.seq : null;
49
+ this.resumeAttempted = this.sessionId !== undefined;
50
+ }
51
+ catch {
52
+ // First run or unreadable file: start a fresh session.
53
+ }
54
+ // connect() 自身兜底 token 失败并 scheduleReconnect,勿在 start 吞错。
55
+ this.emitStatus('connecting');
56
+ void this.connect();
57
+ }
58
+ emitStatus(status, detail) {
59
+ try { this.hooks?.onStatus?.(status, detail); }
60
+ catch { /* status hook must not break the connection loop */ }
61
+ }
62
+ dispose() {
63
+ this.disposed = true;
64
+ this.clearHeartbeat();
65
+ if (this.reconnectTimer !== undefined)
66
+ clearTimeout(this.reconnectTimer);
67
+ this.socket?.close();
68
+ this.socket = undefined;
69
+ }
70
+ clearHeartbeat() {
71
+ if (this.heartbeat === undefined)
72
+ return;
73
+ clearInterval(this.heartbeat);
74
+ this.heartbeat = undefined;
75
+ }
76
+ scheduleReconnect() {
77
+ if (this.disposed || this.reconnectTimer !== undefined)
78
+ return;
79
+ const delay = RECONNECT_DELAYS[Math.min(this.reconnectAttempt, RECONNECT_DELAYS.length - 1)];
80
+ this.reconnectAttempt += 1;
81
+ this.reconnectTimer = setTimeout(() => {
82
+ this.reconnectTimer = undefined;
83
+ void this.connect();
84
+ }, delay);
85
+ }
86
+ async persistSession() {
87
+ if (this.sessionId === undefined)
88
+ return;
89
+ const payload = JSON.stringify({ sessionId: this.sessionId, seq: this.lastSequence });
90
+ try {
91
+ await mkdir(dirname(this.sessionFile), { recursive: true });
92
+ await writeFile(this.sessionFile, payload, 'utf8');
93
+ }
94
+ catch (error) {
95
+ this.log.warn('cannot persist QQ gateway session: %o', error);
96
+ }
97
+ }
98
+ async connect() {
99
+ if (this.disposed || this.connecting)
100
+ return;
101
+ let token;
102
+ try {
103
+ token = await this.api.ensureToken();
104
+ }
105
+ catch (error) {
106
+ this.emitStatus('error', error instanceof Error ? error.message : String(error));
107
+ this.scheduleReconnect();
108
+ return;
109
+ }
110
+ if (this.socket?.readyState === WebSocket.OPEN || this.socket?.readyState === WebSocket.CONNECTING)
111
+ return;
112
+ this.connecting = true;
113
+ try {
114
+ const url = await this.api.gatewayUrl();
115
+ const socket = new WebSocket(url);
116
+ this.socket = socket;
117
+ socket.on('open', () => {
118
+ this.log.info('QQ gateway connected');
119
+ this.reconnectAttempt = 0;
120
+ this.emitStatus('ready');
121
+ });
122
+ socket.on('message', (raw) => { this.handleFrame(raw, token); });
123
+ socket.on('close', (code, reason) => {
124
+ if (this.socket !== socket)
125
+ return;
126
+ this.socket = undefined;
127
+ this.clearHeartbeat();
128
+ if (this.disposed)
129
+ return;
130
+ this.log.warn('QQ gateway closed (%s %s); reconnecting', code, reason.toString());
131
+ this.emitStatus('closed', `${code} ${reason}`);
132
+ this.scheduleReconnect();
133
+ });
134
+ socket.on('error', (error) => {
135
+ this.log.warn('QQ gateway error: %o', error);
136
+ this.emitStatus('error', error instanceof Error ? error.message : String(error));
137
+ });
138
+ }
139
+ catch (error) {
140
+ this.log.error('QQ gateway connect failed: %o', error);
141
+ this.emitStatus('error', error instanceof Error ? error.message : String(error));
142
+ this.scheduleReconnect();
143
+ }
144
+ finally {
145
+ this.connecting = false;
146
+ }
147
+ }
148
+ handleFrame(raw, token) {
149
+ let payload;
150
+ try {
151
+ payload = JSON.parse(raw.toString());
152
+ }
153
+ catch (error) {
154
+ this.log.warn('ignoring malformed gateway frame: %o', error);
155
+ return;
156
+ }
157
+ if (payload === undefined || typeof payload.op !== 'number')
158
+ return;
159
+ if (typeof payload.s === 'number')
160
+ this.lastSequence = payload.s;
161
+ if (this.config.debug)
162
+ this.log.debug?.('gateway op=%s t=%s', payload.op, payload.t);
163
+ const op = payload.op;
164
+ if (op === 10) {
165
+ const hello = payload.d;
166
+ const interval = typeof hello?.heartbeat_interval === 'number' ? hello.heartbeat_interval : 30_000;
167
+ this.clearHeartbeat();
168
+ this.heartbeat = setInterval(() => {
169
+ if (this.socket?.readyState === WebSocket.OPEN) {
170
+ this.socket.send(JSON.stringify({ op: 1, d: this.lastSequence }));
171
+ }
172
+ }, interval);
173
+ this.identifyOrResume(token);
174
+ return;
175
+ }
176
+ if (op === 7) {
177
+ // Server-requested reconnect: drop the socket; the close handler retries.
178
+ this.socket?.close();
179
+ return;
180
+ }
181
+ if (op === 9) {
182
+ // Invalid session: discard session state and identify fresh.
183
+ this.sessionId = undefined;
184
+ this.lastSequence = null;
185
+ this.resumeAttempted = false;
186
+ void this.persistSession();
187
+ this.socket?.close();
188
+ return;
189
+ }
190
+ if (op !== 0 || typeof payload.t !== 'string')
191
+ return;
192
+ const eventType = payload.t;
193
+ if (eventType === 'READY') {
194
+ const ready = payload.d;
195
+ if (typeof ready?.session_id === 'string') {
196
+ this.sessionId = ready.session_id;
197
+ this.resumeAttempted = true;
198
+ void this.persistSession();
199
+ }
200
+ this.hooks.onReady?.();
201
+ return;
202
+ }
203
+ if (eventType === 'RESUMED') {
204
+ this.log.info('QQ gateway resumed session seq=%s', this.lastSequence);
205
+ this.hooks.onReady?.();
206
+ return;
207
+ }
208
+ if (eventType === 'INTERACTION_CREATE') {
209
+ this.hooks.onInteraction(payload.d);
210
+ return;
211
+ }
212
+ if (eventType === 'C2C_MESSAGE_CREATE'
213
+ || eventType === 'GROUP_AT_MESSAGE_CREATE'
214
+ || eventType === 'AT_MESSAGE_CREATE'
215
+ || eventType === 'DIRECT_MESSAGE_CREATE') {
216
+ this.hooks.onMessage(payload.d, eventType);
217
+ }
218
+ }
219
+ identifyOrResume(token) {
220
+ if (this.socket?.readyState !== WebSocket.OPEN)
221
+ return;
222
+ const intents = this.config.intents ?? DEFAULT_INTENTS;
223
+ if (this.sessionId !== undefined && this.resumeAttempted) {
224
+ // RESUME path: the persisted session_id/seq belong to one specific
225
+ // AppID. Logging them (and the AppID) lets you spot "I switched AppIDs
226
+ // but my gateway session file still points at the old one".
227
+ this.log.info('QQ gateway: resume op=6 (appId=%s session_id=%s seq=%s intents=%s)', this.config.qqAppId ?? this.config.id, this.sessionId, String(this.lastSequence), intents);
228
+ this.socket.send(JSON.stringify({
229
+ op: 6,
230
+ d: { token: `QQBot ${token}`, session_id: this.sessionId, seq: this.lastSequence },
231
+ }));
232
+ return;
233
+ }
234
+ // Fresh IDENTIFY path: print the intents mask we are about to subscribe
235
+ // to. A bot that never receives events but connects fine usually has the
236
+ // wrong mask here.
237
+ this.log.info('QQ gateway: identify op=2 (appId=%s intents=%s sandbox=%s)', this.config.qqAppId ?? this.config.id, intents, String(this.config.sandbox ?? true));
238
+ this.socket.send(JSON.stringify({
239
+ op: 2,
240
+ d: {
241
+ token: `QQBot ${token}`,
242
+ intents,
243
+ shard: [0, 1],
244
+ },
245
+ }));
246
+ }
247
+ }
248
+ //# sourceMappingURL=gateway.js.map
@@ -0,0 +1,318 @@
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
+
16
+ const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
17
+
18
+ function pad(n) { return String(n).padStart(2, '0'); }
19
+ function nowHm(d = new Date()) { return `${pad(d.getHours())}:${pad(d.getMinutes())}`; }
20
+ function today(d = new Date()) { return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`; }
21
+ function localDateOf(ms) { const d = new Date(ms); return today(d); }
22
+ function minutesAgo(hhmm, now = new Date()) {
23
+ const [h, m] = String(hhmm).split(':').map((x) => Number(x));
24
+ if (!Number.isFinite(h) || !Number.isFinite(m)) return undefined;
25
+ return ((now.getHours() * 60 + now.getMinutes()) - (h * 60 + m));
26
+ }
27
+ function inQuietHours(quietHours, now = new Date()) {
28
+ const hm = now.getHours() * 60 + now.getMinutes();
29
+ return (quietHours || []).some((range) => {
30
+ const mm = /^(?:(\d{1,2}):?(\d{2})?)\s*-\s*(?:(\d{1,2}):?(\d{2})?)$/.exec(String(range).trim());
31
+ if (!mm) return false;
32
+ const s = Number(mm[1]) * 60 + Number(mm[2] || 0);
33
+ const e = Number(mm[3]) * 60 + Number(mm[4] || 0);
34
+ return s <= e ? hm >= s && hm <= e : hm >= s || hm <= e;
35
+ });
36
+ }
37
+
38
+ /**
39
+ * @param deps {
40
+ * config, log,
41
+ * persona, // persona lib(loadRole/listRoles/saveRoleField/roleWorkspace/roleDir/dataRoot)
42
+ * pipelines, // per-bot 管线 facade 数组(见 index.js):
43
+ * // { botId, roleId, routes, threads, inbound, withinChatWindowMs, httpApiToken }
44
+ * dshHome // 可选:DSH_HOME 覆盖(测试用)
45
+ * }
46
+ */
47
+ export function createHeartbeatScheduler(deps) {
48
+ const { config, log, persona, dshHome } = deps;
49
+ // 每次 tick 现取管线列表(数组或访问器均可):网页动态增删 bot 即时生效。
50
+ const currentPipelines = () => (typeof deps.pipelines === 'function' ? deps.pipelines() : deps.pipelines);
51
+ let timer = null;
52
+ let stopped = false;
53
+ // 每个 dsh 进程启动后首个心跳 tick 视为「重启后首次」,无视 lastLifeWarnAt 旧节流:
54
+ // 否则重启前设下的节流会跨重启压制非零性提示(例:重启前刚唤醒过 → 重启后要等整个
55
+ // 窗口才再通知,dsh 一直不知道脚本已经没了)。
56
+ let freshLife = true;
57
+
58
+ /** 每个 bot 管线构建 wakeupSession 依赖(含该管线的 botId/roleId/线程/路由/活动时间/生活脚本状态)。 */
59
+ function wakeBaseFor(p) {
60
+ return {
61
+ threads: p.threads,
62
+ routes: p.routes,
63
+ ensureAgent: (sid) => p.inbound.ensureAgent(sid),
64
+ persona,
65
+ botId: p.botId,
66
+ roleId: p.roleId,
67
+ withinChatWindowMs: p.withinChatWindowMs,
68
+ log,
69
+ activityAt: (sid) => p.inbound.userActivityAt(sid),
70
+ // 是否有生活脚本在运行(非零性判定:有脚本在跑才满足,文件存在不算)。
71
+ // 先恢复 dsh 重启前的运行表,再判非零,避免重启后误判「无脚本在跑」。
72
+ lifeActive: async (ws) => {
73
+ await recoverLifeScripts(ws);
74
+ await pruneDeadLifeScripts(ws);
75
+ return (await listRunningLifeScripts(ws)).length > 0;
76
+ },
77
+ };
78
+ }
79
+
80
+ function archiveBaseFor(p) {
81
+ return {
82
+ threads: p.threads,
83
+ ensureAgent: (sid) => p.inbound.ensureAgent(sid),
84
+ persona,
85
+ botId: p.botId,
86
+ roleId: p.roleId,
87
+ log,
88
+ };
89
+ }
90
+
91
+ /** 收集「有绑定 openid、该 bot 管线服务的角色」上下文(无 openid 无法联系则跳过)。 */
92
+ async function roleContexts() {
93
+ const out = [];
94
+ for (const p of currentPipelines()) {
95
+ const role = await persona.loadRole(p.roleId);
96
+ if (!role) {
97
+ log?.warn?.('pygmalion heartbeat: role %s missing (pipeline %s)', p.roleId, p.botId);
98
+ continue;
99
+ }
100
+ const openid = role.binding?.openid;
101
+ if (!openid) continue;
102
+ out.push({ pipeline: p, role, openid });
103
+ }
104
+ return out;
105
+ }
106
+
107
+ /** 各 c2c openid 的最后用户活动时间(来自该管线路由存储,纯用户消息驱动)。 */
108
+ function lastActivityByOpenid(routes) {
109
+ const map = {};
110
+ for (const { record } of routes.entries()) {
111
+ const t = record?.target;
112
+ if (t?.kind === 'c2c' && t.userId && typeof record.lastMsgAt === 'number')
113
+ map[t.userId] = Math.max(map[t.userId] ?? 0, record.lastMsgAt);
114
+ }
115
+ return map;
116
+ }
117
+
118
+ /** 兜底:每 tick 从活跃会话 session log 提取写日期层原始记录(主触发在 inbound / director_send)。 */
119
+ async function refreshRawRecord({ role, openid, pipeline }) {
120
+ const counter = pipeline.threads?.current(`c2c:${openid}`) ?? 0;
121
+ const file = activeSessionFile({ openid, threadCounter: counter, workspace: role.workspace, dshHome, botId: pipeline.botId });
122
+ const charLabel = role.persona?.name || role.roleId || '角色';
123
+ await refreshRawRecordFromSession({ workspace: role.workspace, sessionFile: file, charLabel, log });
124
+ }
125
+
126
+ /** 收集「需要主动唤醒」的任务。 */
127
+ async function computeWakeups(ctxs, now) {
128
+ const out = [];
129
+ for (const ctx of ctxs) {
130
+ const { role, openid, pipeline } = ctx;
131
+ const pr = role.proactive || {};
132
+ if (pr.enabled === false) continue;
133
+ if (inQuietHours(pr.quietHours || [], now)) continue;
134
+ // 未激活:从没聊过一次的角色不主动唤醒(无用户消息历史 = 未激活)。
135
+ const lastBy = lastActivityByOpenid(pipeline.routes);
136
+ const last = lastBy[openid];
137
+ if (last === undefined) continue;
138
+ const state = role.state || {};
139
+ const todayCount = (state.wakeDates && state.wakeDates[today(now)]) || 0;
140
+ const maxWake = pr.maxWakeupsPerDay ?? 5;
141
+ if (todayCount >= maxWake) continue;
142
+ const schedule = role.persona?.schedule ?? {};
143
+ for (const [k, v] of Object.entries(schedule)) {
144
+ const diff = minutesAgo(String(v), now);
145
+ if (diff !== undefined && Math.abs(diff) <= 3) {
146
+ out.push({ ctx, rule: 'schedule', reason: `按你的日程(${k}=${v})`, memoryHint: `现在是 ${nowHm(now)}`, evening: false });
147
+ }
148
+ }
149
+ // 「今日未联系」主动问候:以路由存储最后活动时间为准(用户今天还没发过消息)。
150
+ const contactedToday = localDateOf(last) === today(now);
151
+ if (!contactedToday) {
152
+ const diff = minutesAgo(pr.eveningCheck ?? config.heartbeat?.eveningCheck ?? '20:00', now);
153
+ if (diff !== undefined && diff >= 0 && (state.eveningSentDate ?? '') !== today(now)) {
154
+ out.push({ ctx, rule: 'evening', reason: `ta 今天还没有主动找你`, memoryHint: `现在是 ${nowHm(now)},看看记忆里最近聊过什么,像朋友一样自然地开口`, evening: true });
155
+ }
156
+ }
157
+ }
158
+ return out;
159
+ }
160
+
161
+ /** 收集「需要归档」的任务:用户沉默超时且该日原始记录未主题化。 */
162
+ async function computeArchives(ctxs, now) {
163
+ const ts = Date.now();
164
+ const out = [];
165
+ for (const ctx of ctxs) {
166
+ const { role, openid, pipeline } = ctx;
167
+ const idleLimit = role.proactive?.archiveIdleMinutes ?? config.heartbeat?.archiveIdleMinutes ?? 45;
168
+ if (!idleLimit) continue;
169
+ const last = lastActivityByOpenid(pipeline.routes)[openid];
170
+ if (last === undefined) continue;
171
+ const idleMin = Math.round((ts - last) / 60_000);
172
+ if (idleMin < idleLimit) continue;
173
+ const memDir = join(role.workspace, 'memory');
174
+ let dates = [];
175
+ try { dates = (await readdir(memDir)).filter((n) => DATE_RE.test(n)).sort(); } catch { dates = []; }
176
+ for (const d of dates.slice().reverse()) {
177
+ const hasRaw = await readFile(join(memDir, d, '原始记录.md'), 'utf8').then(() => true).catch(() => false);
178
+ if (!hasRaw) continue;
179
+ const needs = await readFile(join(memDir, d, '索引.md'), 'utf8')
180
+ .then((t) => /(归档日期:|主题化|基础统计|待归档)/.test(t)).catch(() => true);
181
+ if (needs) { out.push({ ctx, date: d, idleMin }); break; }
182
+ }
183
+ }
184
+ return out;
185
+ }
186
+
187
+ /** 记一次主动唤醒(写角色 state.json.wakeDates/eveningSentDate)。 */
188
+ async function bumpState(ctx, { evening = false }) {
189
+ try {
190
+ const state = { ...(ctx.role.state || {}) };
191
+ const key = today();
192
+ state.lastWakeupAt = new Date().toISOString();
193
+ state.wakeDates = { ...(state.wakeDates || {}), [key]: ((state.wakeDates || {})[key] || 0) + 1 };
194
+ if (evening) state.eveningSentDate = key;
195
+ await persona.saveRoleField(ctx.role.roleId, 'state', state);
196
+ } catch (e) { log?.warn?.('heartbeat state write failed: %o', e); }
197
+ }
198
+
199
+ /** ④ 等待脚本(rewake)到期处理:到期且用户这期间没回过 → 唤醒 dsh 继续。 */
200
+ async function rewakeTick(ctxs, now) {
201
+ const ts = now.getTime();
202
+ for (const ctx of ctxs) {
203
+ const { role, openid, pipeline } = ctx;
204
+ const state = { ...(role.state || {}) };
205
+ if (!Array.isArray(state.rewake) || !state.rewake.length) continue;
206
+ const due = state.rewake.filter((r) => r.atMs <= ts);
207
+ if (!due.length) continue;
208
+ const lastBy = lastActivityByOpenid(pipeline.routes);
209
+ for (const r of due) {
210
+ const last = lastBy[openid];
211
+ // 取消语义:从「安排时刻 createdAt」起,用户只要发过任何消息(哪怕在到点之前),
212
+ // 这次等待就自然完成——不再唤醒,节省一次无效调用。
213
+ const bound = r.createdAt ?? r.atMs;
214
+ if (last !== undefined && last >= bound) {
215
+ log?.info?.('pygmalion rewake cancelled for role %s (user replied during wait)', role.roleId);
216
+ state.rewake = state.rewake.filter((x) => x !== r);
217
+ continue;
218
+ }
219
+ try {
220
+ await wakeupSession(wakeBaseFor(pipeline), {
221
+ target: { kind: 'c2c', userId: openid },
222
+ reason: '等待脚本到期',
223
+ memoryHint: `你之前约定到这个点时回来看看 ta:${r.reason}(ta 这段时间没发消息)`,
224
+ });
225
+ log?.info?.('pygmalion heartbeat: rewake due for role %s', role.roleId);
226
+ } catch (e) { log?.warn?.('pygmalion rewake %s failed: %o', role.roleId, e); }
227
+ state.rewake = state.rewake.filter((x) => x !== r);
228
+ }
229
+ try { await persona.saveRoleField(role.roleId, 'state', state); } catch { /* ignore */ }
230
+ }
231
+ }
232
+
233
+ /**
234
+ * ③ 非零性检查:每个绑定 openid 的角色必须「至少有一个生活脚本在运行」。
235
+ * 有脚本在跑 → 角色生活正常,不打搅 dsh;没有任何脚本在运行(非零性破坏)→
236
+ * 节流(warnIntervalMs)后唤醒 dsh,让它创作角色生活经历并程序化为脚本(life_run 启动)。
237
+ * 插件不限制脚本运行时长/次数;「非零」由 dsh 保证。撞车/静默由 wakeupSession 处理。
238
+ */
239
+ async function lifeTick(ctxs, now) {
240
+ if (config.heartbeat?.lifeEnabled === false) return;
241
+ const ts = now.getTime();
242
+ const warnIntervalMs = config.heartbeat?.lifeIntervalMs ?? 3 * 3600 * 1000;
243
+ for (const ctx of ctxs) {
244
+ const { role, openid, pipeline } = ctx;
245
+ const pr = role.proactive || {};
246
+ if (pr.lifeEnabled === false) 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
+ async function runOnce() {
273
+ if (stopped) return;
274
+ const ctxs = await roleContexts();
275
+ const now = new Date();
276
+ // 兜底:从活跃会话 session log 提取写日期层原始记录(主触发在 inbound / director_send)
277
+ for (const ctx of ctxs) {
278
+ try { await refreshRawRecord(ctx); }
279
+ catch (e) { log?.warn?.('pygmalion raw record %s failed: %o', ctx.role.roleId, e); }
280
+ }
281
+ for (const w of await computeWakeups(ctxs, now)) {
282
+ try {
283
+ const r = await wakeupSession(wakeBaseFor(w.ctx.pipeline), {
284
+ target: { kind: 'c2c', userId: w.ctx.openid },
285
+ reason: w.reason,
286
+ memoryHint: w.memoryHint,
287
+ });
288
+ if (r?.ok) await bumpState(w.ctx, { evening: w.evening });
289
+ log?.info?.('pygmalion heartbeat: wakeup %s (%s) ok=%s', w.ctx.role.roleId, w.rule, Boolean(r?.ok));
290
+ } catch (e) { log?.warn?.('pygmalion heartbeat wakeup %s failed: %o', w.ctx.role.roleId, e); }
291
+ }
292
+ await lifeTick(ctxs, now);
293
+ await rewakeTick(ctxs, now);
294
+ for (const a of await computeArchives(ctxs, now)) {
295
+ try {
296
+ await archiveWakeup(archiveBaseFor(a.ctx.pipeline), { target: { kind: 'c2c', userId: a.ctx.openid }, date: a.date });
297
+ log?.info?.('pygmalion heartbeat: archive %s (%s, idle %dmin)', a.ctx.role.roleId, a.date, a.idleMin);
298
+ } catch (e) { log?.warn?.('pygmalion heartbeat archive %s failed: %o', a.ctx.role.roleId, e); }
299
+ }
300
+ }
301
+
302
+ return {
303
+ start() {
304
+ if (timer !== null) return;
305
+ if (config.heartbeat?.enabled === false) { log?.info?.('pygmalion heartbeat disabled by config'); return; }
306
+ freshLife = true; // 本次进程运行期首个 tick 无视旧节流(重启后立刻查一次非零)
307
+ const interval = Math.max(Number(config.heartbeat?.intervalMs) || 60_000, 5_000);
308
+ log?.info?.('pygmalion heartbeat started (interval=%dms, archiveIdle=%dmin, pipelines=%d)', interval, config.heartbeat?.archiveIdleMinutes ?? 45, currentPipelines().length);
309
+ setTimeout(() => { void runOnce(); }, 3_000);
310
+ timer = setInterval(() => { void runOnce().catch((e) => log?.warn?.('pygmalion heartbeat tick error: %o', e)); }, interval);
311
+ },
312
+ stop() {
313
+ stopped = true;
314
+ if (timer !== null) { clearInterval(timer); timer = null; }
315
+ },
316
+ runOnce,
317
+ };
318
+ }