pygmalion 0.1.14 → 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 (81) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +141 -69
  3. package/THIRD_PARTY.md +9 -0
  4. package/docs/ARCHITECTURE.md +66 -107
  5. package/docs/DEPLOY.md +33 -136
  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 -306
  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 -525
  28. package/src/devices/monsterparty-controller.mjs +393 -0
  29. package/src/devices/{doc.mjs → monsterparty-doc.mjs} +60 -69
  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 +117 -95
  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 +120 -41
  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 -143
  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 +216 -168
  68. package/src/voice-defaults.js +13 -0
  69. package/src/voice-mimo.js +139 -95
  70. package/src/voice.js +200 -0
  71. package/src/wakeup.js +76 -35
  72. package/src/web-public/app.js +536 -367
  73. package/src/web-public/index.html +161 -156
  74. package/src/web-public/layout.css +7 -7
  75. package/src/web-public/style.css +12 -8
  76. package/src/web-server.js +158 -89
  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 -253
  81. package/preset/pygmalion-director/preset.yml +0 -3
@@ -1,133 +1,136 @@
1
- /**
2
- * 日期层原始记录提取:从 dsh 会话日志(session.jsonl.zstd)程序化提取真实聊天原文,
3
- * 合并写入 <workspace>/memory/<日期>/原始记录.md。
4
- *
5
- * 设计(docs/代号皮格马利翁正式版设计.md):日期层原文由插件自动从 session log 提取,
6
- * 以 dsh 的会话日志为唯一来源——历史与新消息都在里面,实时写上线前的记录也能进来。
7
- * 该文件同时是话题切片(heartbeat 沉默归档)与 recollect 的输入,路径/行格式与既有归档保持一致。
8
- *
9
- * 触发时机由调用方驱动(用户消息到达 / director_send 发出后延迟刷新,heartbeat 兜底);
10
- * 本模块只负责「读会话文件 → 提取消息 → 按日期分组 → 合并去重写」,保证同一文件的并发写串行不交错。
11
- */
12
- import { writeFile, appendFile, mkdir, readFile } from 'node:fs/promises';
13
- import { join } from 'node:path';
14
- import { cleanUserText, isSystemText, readSessionText, parseEvents, extractMessages } from './session-log.js';
15
-
16
- /** 唤醒/归档/生活情境与 HTTP 推送记录的行首标记(与 wakeup.js / http-api.js 前缀一致)。 */
17
- const INJECTION_LINE = /^\[(唤醒事件|生活窗口|归档任务|设备事件|设备|HTTP 推送记录)/;
18
-
19
- function pad(n) { return String(n).padStart(2, '0'); }
20
- function localDateOf(ms) { const d = new Date(ms); return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`; }
21
- function localTimeOf(ms) { const d = new Date(ms); return `${pad(d.getHours())}:${pad(d.getMinutes())}`; }
22
-
23
- /** 每文件串行写队列:同一文件的写操作逐个排队,防并发交错。 */
24
- const writeQueues = new Map();
25
- function enqueueWrite(file, fn) {
26
- const prev = writeQueues.get(file) ?? Promise.resolve();
27
- const next = prev.then(fn, fn);
28
- writeQueues.set(file, next.catch(() => undefined));
29
- return next;
30
- }
31
-
32
- /**
33
- * 用户消息筛选(source 缺失/测试事件时的文本兜底):命中任一即视为「非真人闲聊」——
34
- * 唤醒/归档/生活情境([唤醒事件] 等)、HTTP 推送记录([HTTP 推送记录])、
35
- * 系统注入(runtime context 等)、纯时间线/附件行、清洗后为空。
36
- * 角色(director_send)消息不经过此过滤:工具调用即真人可感知的发言。
37
- */
38
- export function isConversationalUserText(text) {
39
- const clean = cleanUserText(text);
40
- if (!clean)
41
- return false;
42
- if (INJECTION_LINE.test(clean))
43
- return false;
44
- if (isSystemText(clean))
45
- return false;
46
- return true;
47
- }
48
-
49
- /** 角色显示名:角色人设名 → roleId → '角色'(与 heartbeat 归档一致)。 */
50
- export async function charLabelOf(persona, roleId) {
51
- if (persona?.loadRole !== undefined && roleId) {
52
- try {
53
- const role = await persona.loadRole(roleId);
54
- if (role?.persona?.name)
55
- return role.persona.name;
56
- }
57
- catch { /* fall through */ }
58
- }
59
- return roleId || '角色';
60
- }
61
-
62
- /**
63
- * 提取会话事件中的聊天原文并合并写入对应日期的原始记录。
64
- * - extractMessages 已有 cleanUserText/isSystemText/文本去重;此处再对 user 消息过
65
- * isConversationalUserText,排除唤醒/归档/生活注入(走 agent.send 会记入会话日志);
66
- * - 按消息自身本地日期分组,写入 memory/<day>/原始记录.md(活跃线程历史日期也会归档);
67
- * - 行格式 `- [YYYY-MM-DD HH:MM] <标签>: <文本>`;文件不存在先写头部;
68
- * - 已有行去重:同一会话被多次提取不会重复(读取现有行集合并追加缺失行)。
69
- * 返回本次新写入的行数。
70
- */
71
- export async function writeRawRecordFromEvents({ workspace, charLabel, userLabel = '用户', events }) {
72
- const msgs = extractMessages(events);
73
- const byDay = new Map();
74
- for (const m of msgs) {
75
- if (m.time === undefined)
76
- continue;
77
- if (m.role === 'user' && !isConversationalUserText(m.text))
78
- continue;
79
- const day = localDateOf(m.time);
80
- let list = byDay.get(day);
81
- if (list === undefined) {
82
- list = [];
83
- byDay.set(day, list);
84
- }
85
- list.push(m);
86
- }
87
- let added = 0;
88
- for (const [day, list] of byDay) {
89
- list.sort((a, b) => (a.time ?? 0) - (b.time ?? 0));
90
- const dir = join(workspace, 'memory', day);
91
- const file = join(dir, '原始记录.md');
92
- const header = `# ${day} 原始记录\n\n> 从会话日志提取(忠实原文,非转述)。\n\n- 用户:${userLabel}\n- 角色:${charLabel}\n\n`;
93
- added += await enqueueWrite(file, async () => {
94
- await mkdir(dir, { recursive: true });
95
- const existing = await readFile(file, 'utf8').then((t) => new Set(t.split('\n'))).catch(() => undefined);
96
- const fresh = [];
97
- for (const m of list) {
98
- const label = m.role === 'character' ? charLabel : userLabel;
99
- const line = `- [${localDateOf(m.time)} ${localTimeOf(m.time)}] ${label}: ${m.text}`;
100
- if (existing !== undefined && existing.has(line))
101
- continue;
102
- if (existing !== undefined)
103
- existing.add(line);
104
- fresh.push(line);
105
- }
106
- if (fresh.length === 0)
107
- return 0;
108
- const block = fresh.join('\n') + '\n';
109
- if (existing !== undefined)
110
- await appendFile(file, block, 'utf8');
111
- else
112
- await writeFile(file, header + block, 'utf8');
113
- return fresh.length;
114
- });
115
- }
116
- return added;
117
- }
118
-
119
- /**
120
- * 从单个会话文件提取并写入原始记录(文件不存在/不可读返回 0,不抛错)。
121
- * 由 inbound(用户消息)、director_send(角色消息)、heartbeat(兜底)调用。
122
- */
123
- export async function refreshRawRecordFromSession({ workspace, sessionFile, charLabel, userLabel = '用户', log }) {
124
- let events;
125
- try {
126
- events = parseEvents(await readSessionText(sessionFile));
127
- }
128
- catch (error) {
129
- log?.debug?.('pygmalion: 读取会话 %s 失败(可能无文件): %o', sessionFile, error);
130
- return 0;
131
- }
132
- return writeRawRecordFromEvents({ workspace, charLabel, userLabel, events });
133
- }
1
+ /**
2
+ * 日期层原始记录提取:从 dsh 会话日志(session.jsonl.zstd)程序化提取真实聊天原文,
3
+ * 合并写入 <workspace>/memory/<日期>/原始记录.md。
4
+ *
5
+ * 设计(docs/代号皮格马利翁正式版设计.md):日期层原文由插件自动从 session log 提取,
6
+ * 以 dsh 的会话日志为唯一来源——历史与新消息都在里面,实时写上线前的记录也能进来。
7
+ * 该文件同时是话题切片(heartbeat 沉默归档)与 recollect 的输入,路径/行格式与既有归档保持一致。
8
+ *
9
+ * 触发时机由调用方驱动(用户消息到达 / director_send 发出后延迟刷新,heartbeat 兜底);
10
+ * 本模块只负责「读会话文件 → 提取消息 → 按日期分组 → 合并去重写」,保证同一文件的并发写串行不交错。
11
+ */
12
+ import { writeFile, appendFile, mkdir, readFile } from 'node:fs/promises';
13
+ import { join } from 'node:path';
14
+ import { cleanUserText, isSystemText, readSessionText, parseEvents, extractMessages } from './session-log.js';
15
+ import { readSessionEvents, sessionMissing } from './dsh-runtime.js';
16
+
17
+ /** 唤醒/归档/生活情境与 HTTP 推送记录的行首标记(与 wakeup.js / http-api.js 前缀一致)。 */
18
+ const INJECTION_LINE = /^\[(唤醒事件|生活窗口|归档任务|设备事件|设备|HTTP 推送记录)/;
19
+
20
+ function pad(n) { return String(n).padStart(2, '0'); }
21
+ function localDateOf(ms) { const d = new Date(ms); return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`; }
22
+ function localTimeOf(ms) { const d = new Date(ms); return `${pad(d.getHours())}:${pad(d.getMinutes())}`; }
23
+
24
+ /** 每文件串行写队列:同一文件的写操作逐个排队,防并发交错。 */
25
+ const writeQueues = new Map();
26
+ function enqueueWrite(file, fn) {
27
+ const prev = writeQueues.get(file) ?? Promise.resolve();
28
+ const next = prev.then(fn, fn);
29
+ writeQueues.set(file, next.catch(() => undefined));
30
+ return next;
31
+ }
32
+
33
+ /**
34
+ * 用户消息筛选(source 缺失/测试事件时的文本兜底):命中任一即视为「非真人闲聊」——
35
+ * 唤醒/归档/生活情境([唤醒事件] 等)、HTTP 推送记录([HTTP 推送记录])、
36
+ * 系统注入(runtime context 等)、纯时间线/附件行、清洗后为空。
37
+ * 角色(director_send)消息不经过此过滤:工具调用即真人可感知的发言。
38
+ */
39
+ export function isConversationalUserText(text) {
40
+ const clean = cleanUserText(text);
41
+ if (!clean)
42
+ return false;
43
+ if (INJECTION_LINE.test(clean))
44
+ return false;
45
+ if (isSystemText(clean))
46
+ return false;
47
+ return true;
48
+ }
49
+
50
+ /** 角色显示名:角色人设名 → roleId → '角色'(与 heartbeat 归档一致)。 */
51
+ export async function charLabelOf(persona, roleId) {
52
+ if (persona?.loadRole !== undefined && roleId) {
53
+ try {
54
+ const role = await persona.loadRole(roleId);
55
+ if (role?.persona?.name)
56
+ return role.persona.name;
57
+ }
58
+ catch { /* fall through */ }
59
+ }
60
+ return roleId || '角色';
61
+ }
62
+
63
+ /**
64
+ * 提取会话事件中的聊天原文并合并写入对应日期的原始记录。
65
+ * - extractMessages 已有 cleanUserText/isSystemText/文本去重;此处再对 user 消息过
66
+ * isConversationalUserText,排除唤醒/归档/生活注入(走 agent.send 会记入会话日志);
67
+ * - 按消息自身本地日期分组,写入 memory/<day>/原始记录.md(活跃线程历史日期也会归档);
68
+ * - 行格式 `- [YYYY-MM-DD HH:MM] <标签>: <文本>`;文件不存在先写头部;
69
+ * - 已有行去重:同一会话被多次提取不会重复(读取现有行集合并追加缺失行)。
70
+ * 返回本次新写入的行数。
71
+ */
72
+ export async function writeRawRecordFromEvents({ workspace, charLabel, userLabel = '用户', events }) {
73
+ const msgs = extractMessages(events);
74
+ const byDay = new Map();
75
+ for (const m of msgs) {
76
+ if (m.time === undefined)
77
+ continue;
78
+ if (m.role === 'user' && !isConversationalUserText(m.text))
79
+ continue;
80
+ const day = localDateOf(m.time);
81
+ let list = byDay.get(day);
82
+ if (list === undefined) {
83
+ list = [];
84
+ byDay.set(day, list);
85
+ }
86
+ list.push(m);
87
+ }
88
+ let added = 0;
89
+ for (const [day, list] of byDay) {
90
+ list.sort((a, b) => (a.time ?? 0) - (b.time ?? 0));
91
+ const dir = join(workspace, 'memory', day);
92
+ const file = join(dir, '原始记录.md');
93
+ const header = `# ${day} 原始记录\n\n> 从会话日志提取(忠实原文,非转述)。\n\n- 用户:${userLabel}\n- 角色:${charLabel}\n\n`;
94
+ added += await enqueueWrite(file, async () => {
95
+ await mkdir(dir, { recursive: true });
96
+ const existing = await readFile(file, 'utf8').then((t) => new Set(t.split('\n'))).catch(() => undefined);
97
+ const fresh = [];
98
+ for (const m of list) {
99
+ const label = m.role === 'character' ? charLabel : userLabel;
100
+ const line = `- [${localDateOf(m.time)} ${localTimeOf(m.time)}] ${label}: ${m.text}`;
101
+ if (existing !== undefined && existing.has(line))
102
+ continue;
103
+ if (existing !== undefined)
104
+ existing.add(line);
105
+ fresh.push(line);
106
+ }
107
+ if (fresh.length === 0)
108
+ return 0;
109
+ const block = fresh.join('\n') + '\n';
110
+ if (existing !== undefined)
111
+ await appendFile(file, block, 'utf8');
112
+ else
113
+ await writeFile(file, header + block, 'utf8');
114
+ return fresh.length;
115
+ });
116
+ }
117
+ return added;
118
+ }
119
+
120
+ /**
121
+ * 从单个会话文件提取并写入原始记录(文件不存在/不可读返回 0,不抛错)。
122
+ * 由 inbound(用户消息)、director_send(角色消息)、heartbeat(兜底)调用。
123
+ */
124
+ export async function refreshRawRecordFromSession({ workspace, sessionFile, sessionId, persistence, charLabel, userLabel = '用户', log }) {
125
+ let events;
126
+ try {
127
+ // 运行时只用官方逻辑事件接口;旧文件入口仅留给离线旧格式测试/导入。
128
+ events = persistence ? await readSessionEvents(persistence, sessionId) : parseEvents(await readSessionText(sessionFile));
129
+ }
130
+ catch (error) {
131
+ if (sessionMissing(error) || (!persistence && error?.code === 'ENOENT')) return 0;
132
+ log?.warn?.('pygmalion: 聊天记录读取失败,未推进归档状态: %o', error);
133
+ throw error;
134
+ }
135
+ return writeRawRecordFromEvents({ workspace, charLabel, userLabel, events });
136
+ }
@@ -0,0 +1,26 @@
1
+ /** 身份由适配器、账号作用域和外部主体共同标识,不以裸用户 ID 判等。 */
2
+ export function peerIdentity(value) {
3
+ const fields = ['adapterId', 'accountId', 'peerId'];
4
+ if (!value || fields.some(key => typeof value[key] !== 'string' || !value[key].trim())) throw new Error('通信身份缺少适配器、账号作用域或主体标识');
5
+ return Object.freeze(Object.fromEntries(fields.map(key => [key, value[key]])));
6
+ }
7
+ export const samePeer = (left, right) => Boolean(left && right
8
+ && ['adapterId', 'accountId', 'peerId'].every(key => typeof left[key] === 'string' && left[key].trim() && left[key] === right[key]));
9
+
10
+ /** 新目标携带 identity;旧 QQ 私聊仍可读取旧绑定,显式作用域必须相符。 */
11
+ export function matchesRoleTarget(role, target, scope) {
12
+ if (!role || !['direct', 'c2c'].includes(target?.kind)) return false;
13
+ const binding = role.binding ?? {};
14
+ if (target.identity) {
15
+ if (binding.peer) return samePeer(binding.peer, target.identity);
16
+ return target.identity.adapterId === 'qq-official' && target.identity.peerId === binding.openid
17
+ && Boolean(binding.botAppId) && target.identity.accountId === binding.botAppId;
18
+ }
19
+ if (target.kind !== 'c2c' || target.userId !== binding.openid || !binding.openid) return false;
20
+ if (binding.peer && binding.peer.adapterId !== 'qq-official') return false;
21
+ return (!scope?.adapterId || scope.adapterId === 'qq-official')
22
+ && (!scope?.accountId || !binding.botAppId || scope.accountId === binding.botAppId);
23
+ }
24
+
25
+ export const bindingStamp = role => JSON.stringify([role?.persona?.owner, role?.binding?.peer,
26
+ role?.binding?.botAppId, role?.binding?.openid, role?.binding?.revision ?? 0]);
package/src/persona.js CHANGED
@@ -24,7 +24,8 @@ import { fileURLToPath } from 'node:url';
24
24
  import path from 'node:path';
25
25
  import { homedir } from 'node:os';
26
26
  import { scryptSync, randomBytes, timingSafeEqual, createHash } from 'node:crypto';
27
- import { deviceDocMarkdown } from './devices/doc.mjs';
27
+ import { normalizeRoleplayConfig } from './roleplay-config.js';
28
+ import { peerIdentity, samePeer } from './peer-identity.js';
28
29
 
29
30
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
30
31
 
@@ -54,6 +55,7 @@ export const DEFAULT_PROACTIVE = {
54
55
  export function openidFromSessionId(sessionId) {
55
56
  const stripped = String(sessionId ?? '').split('#')[0];
56
57
  const parts = stripped.split(':');
58
+ if (parts[0] !== 'qq') return undefined;
57
59
  // 新格式:qq:v2:<botId>:<scope>:<id>(parts[1]===v2,parts[3]===scope)
58
60
  if (parts[1] === 'v2' && (parts[3] === 'c2c' || parts[3] === 'group' || parts[3] === 'channel') && parts[4] != null && parts[4].length > 0)
59
61
  return parts[4];
@@ -184,11 +186,12 @@ export async function loadDevice(deviceId) {
184
186
  if (!deviceId) return null;
185
187
  return await readJson(devicePath(deviceId), null);
186
188
  }
187
- /** 建设备并回写账号 deviceIds。kind v1 仅 'monsterparty'。 */
188
- export async function createDevice({ owner, alias, kind = 'monsterparty' }) {
189
- if (!owner || !String(alias ?? '').trim()) return null;
189
+ export async function saveDevice(device) { await atomicWriteJson(devicePath(device.id), device); }
190
+ /** 建设备并回写账号 deviceIds;驱动类型由调用方明确选择。 */
191
+ export async function createDevice({ owner, alias, kind, config = {} }) {
192
+ if (!owner || !String(alias ?? '').trim() || !/^[a-z][a-z0-9._-]*$/.test(kind ?? '')) return null;
190
193
  const id = `dev-${randomBytes(8).toString('hex')}`;
191
- const device = { id, owner, kind, alias: String(alias).trim(), createdAt: Date.now() };
194
+ const device = { id, owner, kind, config, alias: String(alias).trim(), createdAt: Date.now() };
192
195
  await atomicWriteJson(devicePath(id), device);
193
196
  const account = await loadAccount(owner);
194
197
  if (account) {
@@ -222,7 +225,7 @@ export async function deleteDevice(deviceId) {
222
225
  return { removed: true, roleIds };
223
226
  }
224
227
  /** 角色授权设备的文档(memory/设备.md 内容);无授权合法设备 → null。 */
225
- export async function renderDeviceDoc(role) {
228
+ export async function renderDeviceDoc(role, render) {
226
229
  const persona = role?.persona;
227
230
  const ids = Array.isArray(persona?.devices) ? persona.devices : [];
228
231
  if (!ids.length) return null;
@@ -231,7 +234,7 @@ export async function renderDeviceDoc(role) {
231
234
  for (const id of ids) {
232
235
  const dev = await loadDevice(id);
233
236
  if (!dev || dev.owner !== owner) continue; // 只渲染存在且属于本账号的
234
- parts.push(deviceDocMarkdown(dev));
237
+ parts.push(render ? await render(dev) : `# 设备:${dev.alias}\n\n标识:${dev.id}\n驱动:${dev.kind}\n使用前加载对应设备 skill;能力以驱动声明为准。`);
235
238
  }
236
239
  return parts.length ? parts.join('\n\n') : null;
237
240
  }
@@ -265,14 +268,26 @@ export async function loadRole(roleId) {
265
268
  if (!existsSync(join(dir, 'persona.json'))) return null;
266
269
  const persona = await roleJson(roleId, 'persona.json', null);
267
270
  if (!persona) return null;
271
+ const savedProactive = await roleJson(roleId, 'proactive.json', {});
272
+ // 兼容旧配置:已移除的发送审查字段不再进入运行时。
273
+ delete savedProactive.messageReview;
268
274
  return {
269
275
  roleId,
270
276
  persona,
271
277
  model: { ...DEFAULT_MODEL, ...(await roleJson(roleId, 'model.json', {})) },
272
- proactive: { ...DEFAULT_PROACTIVE, ...(await roleJson(roleId, 'proactive.json', {})) },
278
+ roleplay: normalizeRoleplayConfig(await roleJson(roleId, 'roleplay.json', {})),
279
+ proactive: {
280
+ ...DEFAULT_PROACTIVE,
281
+ ...savedProactive,
282
+ memeCollection: {
283
+ ...DEFAULT_PROACTIVE.memeCollection,
284
+ ...(savedProactive.memeCollection ?? {}),
285
+ vision: { ...DEFAULT_PROACTIVE.memeCollection.vision, ...(savedProactive.memeCollection?.vision ?? {}) },
286
+ },
287
+ },
273
288
  binding: await roleJson(roleId, 'binding.json', {}),
274
- state: await roleJson(roleId, 'state.json', {}),
275
- voice: await roleJson(roleId, 'voice/mimo.json', {}),
289
+ state: await roleJson(roleId, 'state.json', {}),
290
+ voice: await roleJson(roleId, 'voice/mimo.json', {}),
276
291
  workspace: roleWorkspace(roleId),
277
292
  };
278
293
  }
@@ -315,17 +330,50 @@ export async function createRole({ accountId, persona }) {
315
330
  return roleId;
316
331
  }
317
332
  export async function deleteRole(roleId) {
318
- const { rm } = await import('node:fs/promises');
319
- await rm(roleDir(roleId), { recursive: true, force: true });
320
- for (const acc of await listAccounts()) {
321
- if ((acc.roleIds || []).includes(roleId)) {
322
- acc.roleIds = acc.roleIds.filter((r) => r !== roleId);
323
- await saveAccount(acc);
333
+ return serializeRole(roleId, async () => {
334
+ const { rm } = await import('node:fs/promises');
335
+ await rm(roleDir(roleId), { recursive: true, force: true });
336
+ for (const acc of await listAccounts()) {
337
+ if ((acc.roleIds || []).includes(roleId)) {
338
+ acc.roleIds = acc.roleIds.filter((r) => r !== roleId);
339
+ await saveAccount(acc);
340
+ }
324
341
  }
325
- }
342
+ });
326
343
  }
327
344
 
328
345
  // ---------------------------------------------------------------- 绑定 --
346
+ const roleQueues = new Map();
347
+ function serializeRole(roleId, action) {
348
+ const key = join(dataRoot(), 'roles', safeId(roleId));
349
+ const pending = (roleQueues.get(key) ?? Promise.resolve()).catch(() => {}).then(action);
350
+ roleQueues.set(key, pending);
351
+ return pending.finally(() => { if (roleQueues.get(key) === pending) roleQueues.delete(key); });
352
+ }
353
+
354
+ /** 规范化身份的首聊绑定;调用方只能为已确认的实时私人入站显式允许新绑定。 */
355
+ export async function bindRoleIdentity(roleId, value, { allowNewBinding = false } = {}) {
356
+ const identity = peerIdentity(value);
357
+ return serializeRole(roleId, async () => {
358
+ const role = await loadRole(roleId);
359
+ if (!role) return { status: 'no-role' };
360
+ const existing = role.binding.peer ?? (role.binding.openid && role.binding.botAppId
361
+ ? { adapterId: 'qq-official', accountId: role.binding.botAppId, peerId: role.binding.openid } : undefined);
362
+ if (existing) return { status: samePeer(existing, identity) ? 'already' : 'mismatch', role };
363
+ // 无账号作用域的历史绑定不能由另一种接入猜测认领。
364
+ if (role.binding.openid) {
365
+ if (!allowNewBinding || identity.adapterId !== 'qq-official' || role.binding.openid !== identity.peerId) return { status: 'mismatch', role };
366
+ // 历史 QQ 记录缺 AppID 时,仅由当前角色的实时 QQ 入站补全作用域。
367
+ await saveRoleField(roleId, 'binding', { ...role.binding, peer: identity, botAppId: identity.accountId });
368
+ return { status: 'already', role: await loadRole(roleId) };
369
+ }
370
+ if (!allowNewBinding) return { status: 'not-eligible', role };
371
+ const binding = { ...role.binding, peer: identity, revision: (role.binding.revision ?? 0) + 1 };
372
+ if (identity.adapterId === 'qq-official') Object.assign(binding, { openid: identity.peerId, botAppId: identity.accountId });
373
+ await saveRoleField(roleId, 'binding', binding);
374
+ return { status: 'bound', role: await loadRole(roleId) };
375
+ });
376
+ }
329
377
  /**
330
378
  * openid 绑定到角色(修 D5):
331
379
  * 未绑定 → 首聊自动绑定为拥有者(记录服务该角色的 bot AppID),返回 { status:'bound' }
@@ -333,22 +381,41 @@ export async function deleteRole(roleId) {
333
381
  * 已绑定不同 openid → { status:'mismatch' }(拒绝,不覆盖)
334
382
  */
335
383
  export async function bindRoleOpenid(roleId, openid, botAppId) {
336
- const role = await loadRole(roleId);
337
- if (!role) return { status: 'no-role' };
338
- if (!openid) return { status: 'no-openid' };
339
- const existing = role.binding.openid;
340
- if (existing) return existing === openid ? { status: 'already', role } : { status: 'mismatch', role };
341
- role.binding.openid = openid;
342
- if (botAppId) role.binding.botAppId = String(botAppId);
343
- await saveRoleField(roleId, 'binding', role.binding);
344
- return { status: 'bound', role: await loadRole(roleId) };
384
+ if (botAppId && openid) return bindRoleIdentity(roleId,
385
+ { adapterId: 'qq-official', accountId: String(botAppId), peerId: openid }, { allowNewBinding: true });
386
+ return serializeRole(roleId, async () => {
387
+ const role = await loadRole(roleId);
388
+ if (!role) return { status: 'no-role' };
389
+ if (!openid) return { status: 'no-openid' };
390
+ const existing = role.binding.openid;
391
+ if (role.binding.peer && role.binding.peer.adapterId !== 'qq-official') return { status: 'mismatch', role };
392
+ if (existing) return existing === openid ? { status: 'already', role } : { status: 'mismatch', role };
393
+ role.binding.openid = openid;
394
+ role.binding.revision = (role.binding.revision ?? 0) + 1;
395
+ if (botAppId) role.binding.botAppId = String(botAppId);
396
+ await saveRoleField(roleId, 'binding', role.binding);
397
+ return { status: 'bound', role: await loadRole(roleId) };
398
+ });
345
399
  }
346
400
  /** 重置绑定(管理网页"支持重置绑定")。 */
347
401
  export async function resetRoleBinding(roleId) {
348
- const role = await loadRole(roleId);
349
- if (!role) return null;
350
- await saveRoleField(roleId, 'binding', { ...role.binding, openid: undefined });
351
- return await loadRole(roleId);
402
+ return serializeRole(roleId, async () => {
403
+ const role = await loadRole(roleId);
404
+ if (!role) return null;
405
+ await saveRoleField(roleId, 'binding', { ...role.binding, peer: undefined, openid: undefined, revision: (role.binding.revision ?? 0) + 1 });
406
+ return await loadRole(roleId);
407
+ });
408
+ }
409
+
410
+ /** 角色状态的读改写使用同一角色队列,避免后台任务覆盖新等待或删除后重建目录。 */
411
+ export async function updateRoleState(roleId, update) {
412
+ return serializeRole(roleId, async () => {
413
+ const role = await loadRole(roleId);
414
+ if (!role) return null;
415
+ const state = await update({ ...role.state });
416
+ await saveRoleField(roleId, 'state', state);
417
+ return state;
418
+ });
352
419
  }
353
420
 
354
421
  // ---------------------------------------------------------------- 运行时 --
@@ -366,7 +433,7 @@ export async function isDirectorSession(sessionId) {
366
433
  const openid = openidFromSessionId(sessionId);
367
434
  if (!openid) return false;
368
435
  const role = await resolveOpenidRuntime(openid);
369
- return role ? Boolean(role.persona) : false;
436
+ return role ? isRoleDirectorSession(role.roleId, sessionId) : false;
370
437
  }
371
438
 
372
439
  /** 只读:会话所属角色的工作区路径。未绑定 → null。 */
@@ -374,7 +441,7 @@ export async function workspaceOfSession(sessionId) {
374
441
  const openid = openidFromSessionId(sessionId);
375
442
  if (!openid) return null;
376
443
  const role = await resolveOpenidRuntime(openid);
377
- return role ? role.workspace : null;
444
+ return role && await isRoleDirectorSession(role.roleId, sessionId) ? role.workspace : null;
378
445
  }
379
446
 
380
447
  /**
@@ -383,27 +450,36 @@ export async function workspaceOfSession(sessionId) {
383
450
  * 由每个 bot 管线用自己服务的 roleId 调用,避免 openid→单角色查表的歧义。
384
451
  */
385
452
  export async function isRoleDirectorSession(roleId, sessionId) {
453
+ const base = String(sessionId ?? '').split('#')[0];
454
+ if (!/^qq:v2:(?:[^:]+:)?c2c:[^:]+$/.test(base)) return false;
386
455
  const openid = openidFromSessionId(sessionId);
387
456
  if (!openid) return false;
388
457
  const role = await loadRole(roleId);
389
458
  return role ? role.binding.openid === openid && Boolean(role.persona) : false;
390
459
  }
391
460
 
392
- /** 安排角色延时唤醒(director_send reawake 参数)。写 role state.json.rewake。 */
393
- export async function scheduleRewake(roleId, minutes, reason) {
461
+ /**
462
+ * 安排角色延时唤醒(director_send reawake 参数)。写 role state.json.rewake。
463
+ * replaceId 只用于替换一次消息参数校验失败时保留下来的兜底安排;普通调用仍可并存多个等待。
464
+ */
465
+ export async function scheduleRewake(roleId, minutes, reason, { replaceId } = {}) {
466
+ return serializeRole(roleId, async () => {
394
467
  const role = await loadRole(roleId);
395
468
  if (!role) return { ok: false, atMs: 0, error: '角色不存在' };
396
469
  const minutesN = Math.min(Math.max(Number(minutes) || 5, 1), 1440);
397
470
  const atMs = Date.now() + minutesN * 60_000;
398
471
  const createdAt = Date.now();
472
+ const id = randomBytes(8).toString('hex');
399
473
  // 只保留「尚未到期」的等待;最多保留 MAX_PENDING-1 条旧待唤醒 + 本次,
400
474
  // 防止堆积大量未来唤醒来回重复唤醒。(旧记录若曾触发过会在 heartbeat 侧被移除)
401
475
  const MAX_PENDING = 5;
402
476
  const state = { ...role.state, rewake: role.state.rewake ?? [] };
403
- const pending = (Array.isArray(state.rewake) ? state.rewake : []).filter((r) => r.atMs > createdAt);
404
- state.rewake = [...pending.slice(-(MAX_PENDING - 1)), { atMs, reason: String(reason ?? '').trim() || '按你的安排再回来看看', createdAt }];
477
+ const pending = (Array.isArray(state.rewake) ? state.rewake : [])
478
+ .filter((r) => r.atMs > createdAt && (replaceId === undefined || r.id !== replaceId));
479
+ state.rewake = [...pending.slice(-(MAX_PENDING - 1)), { id, atMs, reason: String(reason ?? '').trim() || '到时重新观察当前情境', createdAt }];
405
480
  await saveRoleField(roleId, 'state', state);
406
- return { ok: true, atMs };
481
+ return { ok: true, atMs, id };
482
+ });
407
483
  }
408
484
 
409
485
  // ---------------------------------------------------------------- 记忆 --
@@ -424,6 +500,8 @@ export function personaMarkdown(persona) {
424
500
  '',
425
501
  '## 说话风格',
426
502
  persona.speakingStyle || '(待补充)',
503
+ '',
504
+ '> 语言示例只说明说话方式,不是固定答复,也不表示示例事件已经发生;不可作为共同记忆。',
427
505
  ].filter((l) => l !== null);
428
506
  if (Object.keys(s).length > 0) {
429
507
  lines.push('', '## 日程', ...Object.entries(s).map(([k, v]) => `- ${k}: ${v}`));
@@ -436,7 +514,7 @@ const ABOUT_TA_TEMPLATE = [
436
514
  '# 关于TA(特殊记忆)',
437
515
  '',
438
516
  '> 这是你对“TA”的独立记忆:对 TA 的印象、重要事件、TA 的事物。',
439
- '> 由你(导演)直接编辑维护;日常不需要读写,只在值得记/需要回忆时用 recollect 读取。',
517
+ '> 由你直接编辑维护;日常不需要读写,只在值得记/需要回忆时用 recollect 读取。',
440
518
  '> 每次聊天中有值得记住的(TA 的喜好、经历、对你的称呼、重要约定),更新到这里。',
441
519
  '> 保持精简、具体,用 TA 自己的说法;不要放设定、不要转述成第三人称旁白。',
442
520
  '',
@@ -450,14 +528,15 @@ const MEMORY_INDEX_TEMPLATE = [
450
528
  '',
451
529
  '> 本文件索引各日期聊天的整体内容,供新会话快速掌握既往情况。',
452
530
  '> 由归档任务维护:每归档一个日期,即按叙事三要素(时间、地点、人物)为该日全部事件补写条目,',
453
- '> 严格概括、不遗漏信息。',
531
+ '> 严格概括、不遗漏信息。保留说话者、知情范围、提议或已确认约定、未消退的情绪及原因。',
532
+ '> 区分实际发生、对方转述、推测和未定事项,保留最近话轮的指代与承接;语言示例不作为事实记录。',
454
533
  '',
455
534
  '(暂无归档条目。归档后在此按日期补充:**YYYY-MM-DD** — 该日全部事件,每件按 时间|地点|人物|概要 记录)',
456
535
  '',
457
536
  ].join('\n');
458
537
 
459
538
  /** 确保角色记忆目录就绪、人物设定.md 为最新渲染、关于TA.md 与 索引.md 首次就位。 */
460
- export async function syncRoleMemory(role) {
539
+ export async function syncRoleMemory(role, options = {}) {
461
540
  const memory = join(role.workspace, 'memory');
462
541
  await mkdir(memory, { recursive: true });
463
542
  if (role.persona) {
@@ -465,7 +544,7 @@ export async function syncRoleMemory(role) {
465
544
  }
466
545
  // 设备文档:角色授权设备 → memory/设备.md(preset 开场读);无授权 → 删除(撤选不残留)。
467
546
  const devFile = join(memory, '设备.md');
468
- const devDoc = await renderDeviceDoc(role);
547
+ const devDoc = await renderDeviceDoc(role, options.renderDevice);
469
548
  if (devDoc) {
470
549
  await atomicWrite(devFile, devDoc + '\n');
471
550
  } else {