pygmalion 0.1.15 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +141 -70
  3. package/THIRD_PARTY.md +9 -0
  4. package/docs/ARCHITECTURE.md +66 -108
  5. package/docs/DEPLOY.md +33 -137
  6. package/docs/DEVELOPMENT.md +63 -0
  7. package/docs/DEVICE.md +56 -47
  8. package/docs/EXTENSIONS.md +176 -0
  9. package/docs/PRESET.md +21 -63
  10. package/docs/UPGRADE-0.2.md +52 -0
  11. package/package.json +52 -33
  12. package/preset/pygmalion-director/cordis.patch.yml +234 -0
  13. package/preset/pygmalion-director/pygmalion-tools.js +43 -41
  14. package/scripts/start-local-test.mjs +45 -45
  15. package/skills/pygmalion-life-scripts/SKILL.md +12 -0
  16. package/skills/pygmalion-meme-maintenance/SKILL.md +12 -0
  17. package/skills/pygmalion-memory-archive/SKILL.md +24 -0
  18. package/skills/pygmalion-toy-control/SKILL.md +16 -0
  19. package/src/agent-life.js +608 -606
  20. package/src/archive-tools.js +9 -0
  21. package/src/bot-factory.js +129 -311
  22. package/src/bots.js +264 -275
  23. package/src/channel-qq.js +262 -0
  24. package/src/config.js +69 -68
  25. package/src/delivery-receipt.js +36 -0
  26. package/src/delivery-scope.js +20 -0
  27. package/src/devices/manager.mjs +80 -570
  28. package/src/devices/monsterparty-controller.mjs +393 -0
  29. package/src/devices/{doc.mjs → monsterparty-doc.mjs} +60 -71
  30. package/src/devices/monsterparty.mjs +294 -294
  31. package/src/devices/pb.mjs +110 -110
  32. package/src/devices/registry.mjs +19 -0
  33. package/src/devices/script-helper.mjs +45 -0
  34. package/src/devices/scripts.mjs +109 -0
  35. package/src/devices/service.mjs +254 -0
  36. package/src/director-messages.js +35 -0
  37. package/src/dsh-runtime.js +17 -0
  38. package/src/extension-config.js +20 -0
  39. package/src/extensions.js +118 -0
  40. package/src/heartbeat.js +118 -97
  41. package/src/http-api.js +519 -509
  42. package/src/inbound.js +36 -207
  43. package/src/index.js +109 -37
  44. package/src/llm-provider.js +214 -171
  45. package/src/meme-worker.js +35 -39
  46. package/src/memebox.js +1 -1
  47. package/src/memory-recall.js +55 -0
  48. package/src/memory-write.js +136 -133
  49. package/src/peer-identity.js +26 -0
  50. package/src/persona.js +132 -69
  51. package/src/role-agent.js +155 -0
  52. package/src/role-runtime.js +65 -0
  53. package/src/roleplay-config.js +37 -0
  54. package/src/roleplay-format.js +37 -0
  55. package/src/roleplay-generation.js +36 -0
  56. package/src/roleplay-materials.js +113 -0
  57. package/src/roleplay-output.js +19 -0
  58. package/src/roleplay-parallel.js +239 -0
  59. package/src/roleplay-session.js +128 -0
  60. package/src/roleplay-worker.js +10 -0
  61. package/src/session-log.js +180 -172
  62. package/src/setup-agent.js +92 -100
  63. package/src/skills.js +97 -0
  64. package/src/slash-commands.js +155 -142
  65. package/src/speech-input.js +20 -0
  66. package/src/threads.js +2 -1
  67. package/src/tools.js +226 -254
  68. package/src/voice-defaults.js +13 -0
  69. package/src/voice-mimo.js +139 -125
  70. package/src/voice.js +200 -0
  71. package/src/wakeup.js +85 -66
  72. package/src/web-public/app.js +542 -382
  73. package/src/web-public/index.html +161 -158
  74. package/src/web-public/layout.css +7 -7
  75. package/src/web-public/style.css +12 -8
  76. package/src/web-server.js +161 -102
  77. package/src/worker-tools.js +18 -0
  78. package/templates/sample-life.mjs +59 -59
  79. package/templates/sample-toy.mjs +33 -33
  80. package/preset/pygmalion-director/agent.cordis.yml +0 -262
  81. package/preset/pygmalion-director/preset.yml +0 -3
  82. package/src/message-review.js +0 -276
package/src/wakeup.js CHANGED
@@ -11,22 +11,24 @@
11
11
  */
12
12
  import { effectiveSessionId } from './inbound.js';
13
13
  import { targetKey } from './threads.js';
14
+ import { readFile } from 'node:fs/promises';
15
+ import { join } from 'node:path';
14
16
 
15
- export const DEFAULT_CHAT_WINDOW_MS = 5 * 60_000;
16
-
17
- /** 当前会话日志中是否有尚未落 tool/result 的指定工具调用。 */
18
- export function hasOpenToolCall(agent, toolName) {
19
- const events = agent?.session?.events;
20
- if (!Array.isArray(events)) return false;
21
- const open = new Map();
22
- for (const event of events) {
23
- if (event?.type === 'tool/call' && event.data?.callId != null)
24
- open.set(String(event.data.callId), event.data.name);
25
- else if (event?.type === 'tool/result' && event.data?.message?.source?.callId != null)
26
- open.delete(String(event.data.message.source.callId));
27
- }
28
- return [...open.values()].includes(toolName);
29
- }
17
+ export const DEFAULT_CHAT_WINDOW_MS = 5 * 60_000;
18
+
19
+ /** 当前会话日志中是否有尚未落 tool/result 的指定工具调用。 */
20
+ export function hasOpenToolCall(agent, toolName) {
21
+ const events = agent?.session?.events;
22
+ if (!Array.isArray(events)) return false;
23
+ const open = new Map();
24
+ for (const event of events) {
25
+ if (event?.type === 'tool/call' && event.data?.callId != null)
26
+ open.set(String(event.data.callId), event.data.name);
27
+ else if (event?.type === 'tool/result' && event.data?.message?.source?.callId != null)
28
+ open.delete(String(event.data.message.source.callId));
29
+ }
30
+ return [...open.values()].includes(toolName);
31
+ }
30
32
 
31
33
  /** Human "now" used inside the wakeup context. */
32
34
  function nowText(now = new Date()) {
@@ -44,16 +46,16 @@ export function buildWakeupContext({ reason, memoryHint, personaName, now = new
44
46
  if (memoryHint != null && `${memoryHint}`.trim().length > 0)
45
47
  parts.push('提示:' + `${memoryHint}`.trim());
46
48
  parts.push('');
47
- parts.push('你是被调度脚本按计划唤醒的。请作为导演,先读取工作区记忆与最近聊天,判断当下的真实情况,');
49
+ parts.push('你是被调度脚本按计划唤醒的。请结合人物设定,先读取工作区记忆与最近聊天,判断当下的真实情况,');
48
50
  parts.push('包括刚才聊过什么、用户是否正在聊天、情境是否已经变化,然后再决定角色此刻是否开口以及');
49
- parts.push('要说什么。角色可以顺势参与对话,也可以选择保持沉默。');
51
+ parts.push('要说什么。角色可以顺势参与对话,也可以选择保持沉默。');
50
52
  return parts.join('\n');
51
53
  }
52
54
 
53
55
  /** 归档任务情境:用户长时间未发言时,把原始记录按话题切片归档为双份记忆并建索引。 */
54
56
  export function buildArchiveContext({ date, workspace, now = new Date() }) {
55
57
  const parts = [
56
- '[归档任务] 角色与用户的对话已沉默一段时间(用户 45 分钟以上未发新消息),现在整理记忆。',
58
+ '[归档任务] 角色与用户的对话已沉默一段时间(用户 45 分钟以上未发新消息),现在整理记忆。',
57
59
  '时间:' + nowText(now),
58
60
  '工作区:' + (workspace ?? ''),
59
61
  ];
@@ -69,12 +71,13 @@ export function buildArchiveContext({ date, workspace, now = new Date() }) {
69
71
  parts.push('3. 每个话题目录里【必须】再写一份 索引.md(概要 / 关键事件 / 情感变化 / 待办与承诺);');
70
72
  parts.push('4. 重写 memory/<目标日期>/索引.md,列出当日各话题、关键事件、情感变化、待办/承诺;');
71
73
  parts.push('5. 若某片段是“对 TA 的印象 / TA 的重要事件 / 值得记住的事”,将要点补充到 memory/关于TA.md;');
74
+ parts.push('记忆概要需保留说话者、知情范围、提议或已确认约定、未消退的情绪及原因;区分实际发生、转述、推测和未定事项,保留话轮指代与承接。语言示例不作为事实归档。');
72
75
  parts.push('6. 全部写完后再遍历 memory/topics/ 下每个目录自查:每个目录必须同时含 原文.md 与 索引.md,且 原文.md 与原始记录对应行逐字一致,发现缺失或错误时补充修正;若当日已归档或无需归档,跳过并在最终文本里说明即可。');
73
76
  return parts.join('\n');
74
77
  }
75
78
 
76
79
  /**
77
- * “脚本事件”情境:角色的生活脚本报来一个生活事件(想用户、心情变化、突发小事件),
80
+ * “脚本事件”情境:角色的生活脚本报来一个生活事件(想用户、心情变化、突发小事件),
78
81
  * 唤醒导演判断此刻是否由角色开口。脚本侧一行 wake() 即可触发。
79
82
  */
80
83
  export function buildScriptEventContext({ event, mood, topic, reason, personaName, now = new Date() }) {
@@ -90,8 +93,8 @@ export function buildScriptEventContext({ event, mood, topic, reason, personaNam
90
93
  if (topic != null && `${topic}`.trim()) parts.push('· 主题:' + topic);
91
94
  parts.push('');
92
95
  parts.push('这是脚本按你设计的事件唤醒你(“有事件就唤醒”:脚本遇到事件就报来,不主动决定开口)。');
93
- parts.push('请作为导演,先读取脚本写下的生活记录(如 life/<名>.log 或工作区记录文件)与最近聊天,');
94
- parts.push('自行判断此刻是否由角色开口:想用户了、想分享刚发生的事,就通过 director_send 发送一条');
96
+ parts.push('请结合人物设定,先读取脚本写下的生活记录(如 life/<名>.log 或工作区记录文件)与最近聊天,');
97
+ parts.push('自行判断此刻是否由角色开口:想用户了、想分享刚发生的事,就通过 director_send 发送一条');
95
98
  parts.push('自然的消息;也可以选择沉默(如刚聊过、用户正忙、当下开口不合适)。脚本只负责报事件,');
96
99
  parts.push('开口与否、如何开口,由你决定。像真实生活那样自然地行动,');
97
100
  parts.push('不要念设定,不要提及“导演 / 脚本 / 系统”。');
@@ -102,7 +105,7 @@ export function buildScriptEventContext({ event, mood, topic, reason, personaNam
102
105
  * “生活窗口”情境:非零性破坏时唤醒导演(没有任何生活脚本在运行),让 dsh 创作角色
103
106
  * 生活经历并程序化为脚本。插件不限制脚本运行时长/次数;“非零”由 dsh 保证。
104
107
  */
105
- export function buildLifeWindowContext({ reason, personaName, hasLifeScript, now = new Date() }) {
108
+ export function buildLifeWindowContext({ reason, personaName, hasLifeScript, now = new Date() }) {
106
109
  const parts = [
107
110
  '[生活窗口] 时间:' + nowText(now),
108
111
  ];
@@ -111,17 +114,17 @@ export function buildLifeWindowContext({ reason, personaName, hasLifeScript, now
111
114
  parts.push('');
112
115
  if (hasLifeScript) {
113
116
  parts.push('你的生活脚本在跑(life/ 下已有脚本,可读 life/.manifest.json 查看清单与最近的运行状态)。');
114
- parts.push('现在你需要自行判断:如果角色此刻会主动联系用户,就用 life_run 查看或调整脚本,根据脚本记录的生活');
117
+ parts.push('现在你需要自行判断:如果角色此刻会主动联系用户,就用 life_run 查看或调整脚本,根据脚本记录的生活');
115
118
  parts.push('决定是否通过 director_send 开口;如果刚聊过、此刻不打扰更合适,也可以选择这轮保持静默。');
116
119
  } else {
117
120
  parts.push('现在是“非零性检查”:当前没有任何生活脚本在运行。这个项目不是聊天机器人——');
118
- parts.push('是要让角色有真实的生活:角色在与用户聊天之外,还应该有自己的生活(一天怎么过、习惯与小事、');
119
- parts.push('心情变化、突发的小事件)。你是导演,职责是创作这些经历、把它们程序化为脚本,');
121
+ parts.push('是要让角色有真实的生活:角色在与用户聊天之外,还应该有自己的生活(一天怎么过、习惯与小事、');
122
+ parts.push('心情变化、突发的小事件)。你可以代入角色或从创作者视角设计这些经历、把它们程序化为脚本,');
120
123
  parts.push('让脚本模拟并记录角色的生活(如写到 life/<名>.log 或工作区文件),这样聊天时角色有真实经历可谈。');
121
124
  parts.push('现在做两件事:');
122
125
  parts.push('1. 新建一个你的生活脚本(新文件,勿覆盖 life/ 下已有文件)——写角色真实的生活细节,');
123
- parts.push(' 不是简单的“用户很久没回就去找用户”;以“有事件就唤醒”为原则:脚本里设计的每个');
124
- parts.push(' 事件(心情变化、到点作息、突发小事件、想用户的时刻)发生时都调用 wake() 报给你,');
126
+ parts.push(' 不是简单的“用户很久没回就去找用户”;以“有事件就唤醒”为原则:脚本里设计的每个');
127
+ parts.push(' 事件(心情变化、到点作息、突发小事件、想用户的时刻)发生时都调用 wake() 报给你,');
125
128
  parts.push(' 由你判断是否开口——没有被唤醒的事件就失去了意义;');
126
129
  parts.push('2. 用 life_run 启动它(立即返回,脚本在后台继续跑,由脚本自己决定何时结束;');
127
130
  parts.push(' 插件只监管展示、不限制运行时长/次数)。');
@@ -129,15 +132,15 @@ export function buildLifeWindowContext({ reason, personaName, hasLifeScript, now
129
132
  parts.push('');
130
133
  parts.push('像真实生活那样自然地行动:可以开口,也可以安静;不要念设定,不要提及“导演 / 脚本 / 系统”。');
131
134
  return parts.join('\n');
132
- }
133
-
134
- export function buildScriptReviewContext({ personaName, now = new Date() }) {
135
- const parts = ['[脚本审阅] 时间:' + nowText(now)];
136
- if (personaName != null && personaName.length > 0) parts.push('角色:' + personaName);
137
- parts.push('', '请审阅当前运行中的脚本及相关日志。');
138
- parts.push('审阅目标:丰富角色交互体验,使用户更能感到角色是活生生的人,有自己的生活,并且符合其社会身份和人设。');
139
- return parts.join('\n');
140
- }
135
+ }
136
+
137
+ export function buildScriptReviewContext({ personaName, now = new Date() }) {
138
+ const parts = ['[脚本审阅] 时间:' + nowText(now)];
139
+ if (personaName != null && personaName.length > 0) parts.push('角色:' + personaName);
140
+ parts.push('', '请审阅当前运行中的脚本及相关日志。');
141
+ parts.push('审阅目标:丰富角色交互体验,使用户更能感到角色是活生生的人,有自己的生活,并且符合其社会身份和人设。');
142
+ return parts.join('\n');
143
+ }
141
144
 
142
145
  /**
143
146
  * 归档唤醒:注入一次归档任务并唤醒 dsh(不发送任何消息给用户)。
@@ -145,15 +148,16 @@ export function buildScriptReviewContext({ personaName, now = new Date() }) {
145
148
  */
146
149
  export async function archiveWakeup(deps, params) {
147
150
  const { target, date, reason } = params;
151
+ if (date !== undefined && !/^\d{4}-\d{2}-\d{2}$/.test(date)) return { ok: false, error: '归档日期必须为 YYYY-MM-DD' };
148
152
  const thread = deps.threads.current(targetKey(target));
149
- const sessionId = effectiveSessionId(target, thread, deps.botId);
153
+ const sessionId = deps.sessionIdFor?.(target) ?? effectiveSessionId(target, thread, deps.botId);
150
154
 
151
155
  // 角色级运行时:工作区 = 本 bot 服务的角色工作区(多 bot 隔离)。
152
156
  let workspace;
153
157
  if (deps.roleId) {
154
158
  const role = await deps.persona?.loadRole?.(deps.roleId);
155
159
  if (role) {
156
- await deps.persona?.syncRoleMemory?.(role);
160
+ await deps.persona?.syncRoleMemory?.(role, { renderDevice: deps.devices?.document });
157
161
  workspace = role.workspace;
158
162
  }
159
163
  }
@@ -162,19 +166,33 @@ export async function archiveWakeup(deps, params) {
162
166
 
163
167
  const text = buildArchiveContext({ date, workspace, reason });
164
168
  deps.log?.info?.('pygmalion archive: waking %s (%s)', sessionId, date ?? reason ?? '(auto)');
165
- await agent.send({
166
- id: `pygarchive:${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`,
167
- role: 'user',
168
- content: [{ type: 'text', text }],
169
- source: { kind: 'system', id: 'pygmalion-archive', name: 'Pygmalion 归档' },
170
- }, 'next-turn', true);
171
- return { ok: true, sessionId };
169
+ if (!deps.subagents?.startActivation) return { ok: false, error: '归档工作会话服务不可用' };
170
+ const controller = new AbortController();
171
+ const rawFile = workspace && date && join(workspace, 'memory', date, '原始记录.md');
172
+ const original = rawFile ? await readFile(rawFile, 'utf8') : undefined;
173
+ const timeout = setTimeout(() => controller.abort(), 8 * 60_000);
174
+ let run;
175
+ try {
176
+ run = await deps.subagents.startActivation({
177
+ provider: 'spawn', label: 'pygmalion-memory-archive', signal: controller.signal, delivery: 'caller',
178
+ request: { parent: agent, agentPreset: 'pygmalion-memory-worker', maxDepth: 1,
179
+ prompt: [{ type: 'text', text: `/pygmalion-memory-archive\n${text}` }] },
180
+ });
181
+ const result = await run.result;
182
+ if (result.stopReason === 'completed' && rawFile) {
183
+ const after = await readFile(rawFile, 'utf8');
184
+ const index = await readFile(join(workspace, 'memory', date, '索引.md'), 'utf8').catch(error => { if (error.code === 'ENOENT') return ''; throw error; });
185
+ if (!after.startsWith(original) || !index.trim() || /待归档/.test(index)) return { ok: false, error: '归档结果未通过原文/索引校验', sessionId: run.childId };
186
+ }
187
+ return { ok: result.stopReason === 'completed', sessionId: run.childId };
188
+ } finally { clearTimeout(timeout); await run?.dispose(); }
172
189
  }
173
190
 
174
- export async function wakeupSession(deps, params) {
175
- const { target, reason, memoryHint, force, kind, event, mood, topic, contextText, interruptTool } = params;
191
+ export async function wakeupSession(deps, params) {
192
+ await deps.assertCurrent?.();
193
+ const { target, reason, memoryHint, force, kind, event, mood, topic, contextText, interruptTool } = params;
176
194
  const thread = deps.threads.current(targetKey(target));
177
- const sessionId = effectiveSessionId(target, thread, deps.botId);
195
+ const sessionId = deps.sessionIdFor?.(target) ?? effectiveSessionId(target, thread, deps.botId);
178
196
 
179
197
  // Collision detection: do not barge into an active / recent conversation.
180
198
  // 设备内部信号(计时结束/脚本结束)不走撞车——它已是当前对话语境的一部分,由 dsh 决定开口与否。
@@ -196,7 +214,7 @@ export async function wakeupSession(deps, params) {
196
214
  if (deps.roleId) {
197
215
  const role = await deps.persona?.loadRole?.(deps.roleId);
198
216
  if (role) {
199
- await deps.persona?.syncRoleMemory?.(role);
217
+ await deps.persona?.syncRoleMemory?.(role, { renderDevice: deps.devices?.document });
200
218
  personaName = role.persona?.name;
201
219
  if (typeof deps.lifeActive === 'function') hasLifeScript = await deps.lifeActive(role.workspace);
202
220
  }
@@ -208,28 +226,29 @@ export async function wakeupSession(deps, params) {
208
226
  deps.log?.error?.('pygmalion wakeup: %s no agent', sessionId);
209
227
  return fail;
210
228
  }
229
+ await deps.assertCurrent?.();
211
230
 
212
231
  let text;
213
232
  if (typeof contextText === 'string' && contextText.length > 0) {
214
233
  text = contextText; // 调用方已构造完整情境(如设备事件)
215
234
  } else if (kind === 'life') text = buildLifeWindowContext({ reason, personaName, hasLifeScript });
216
- else if (kind === 'script-hook') text = buildScriptEventContext({ event, mood, topic, reason, personaName });
217
- else text = buildWakeupContext({ reason, memoryHint, personaName });
218
- deps.log?.info?.('pygmalion wakeup: waking %s (%s)', sessionId, reason ?? '(default)');
219
- let interrupted = false;
220
- // 高优先级设备生命周期事件可以打断仍在执行的 director_send(通常卡在 TTS)。
221
- // 先 cancel 再入队,ReactLoopAgent 才会把该唤醒锁存在下一轮并在中断收敛后立即执行。
222
- if (interruptTool && agent.status === 'running' && hasOpenToolCall(agent, interruptTool)
223
- && typeof agent.cancel === 'function') {
224
- agent.cancel({ kind: 'hook', reason: `Pygmalion 高优先级事件抢占 ${interruptTool}` }, { keepInbox: true });
225
- interrupted = true;
226
- }
227
- await agent.send({
235
+ else if (kind === 'script-hook') text = buildScriptEventContext({ event, mood, topic, reason, personaName });
236
+ else text = buildWakeupContext({ reason, memoryHint, personaName });
237
+ deps.log?.info?.('pygmalion wakeup: waking %s (%s)', sessionId, reason ?? '(default)');
238
+ let interrupted = false;
239
+ // 高优先级设备生命周期事件可以打断仍在执行的 director_send(通常卡在 TTS)。
240
+ // 先 cancel 再入队,ReactLoopAgent 才会把该唤醒锁存在下一轮并在中断收敛后立即执行。
241
+ if (interruptTool && agent.status === 'running' && hasOpenToolCall(agent, interruptTool)
242
+ && typeof agent.cancel === 'function') {
243
+ agent.cancel({ kind: 'hook', reason: `Pygmalion 高优先级事件抢占 ${interruptTool}` }, { keepInbox: true });
244
+ interrupted = true;
245
+ }
246
+ await agent.send({
228
247
  id: `pygwake:${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`,
229
248
  role: 'user',
230
249
  content: [{ type: 'text', text }],
231
- source: { kind: 'user', id: 'pygmalion-wakeup', name: 'Pygmalion 唤醒' },
232
- }, 'next-turn', true);
233
-
234
- return { ok: true, woken: true, sessionId, interrupted };
235
- }
250
+ source: { kind: 'pygmalion-wakeup', form: 'instructions' },
251
+ }, 'next-turn', true);
252
+
253
+ return { ok: true, woken: true, sessionId, interrupted };
254
+ }