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
package/src/wakeup.js CHANGED
@@ -11,9 +11,25 @@
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
17
  export const DEFAULT_CHAT_WINDOW_MS = 5 * 60_000;
16
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
+ }
32
+
17
33
  /** Human "now" used inside the wakeup context. */
18
34
  function nowText(now = new Date()) {
19
35
  return now.toLocaleString('zh-CN', { hour12: false });
@@ -30,16 +46,16 @@ export function buildWakeupContext({ reason, memoryHint, personaName, now = new
30
46
  if (memoryHint != null && `${memoryHint}`.trim().length > 0)
31
47
  parts.push('提示:' + `${memoryHint}`.trim());
32
48
  parts.push('');
33
- parts.push('你是被调度脚本按计划唤醒的。请作为导演,先读取工作区记忆与最近聊天,判断当下的真实情况,');
49
+ parts.push('你是被调度脚本按计划唤醒的。请结合人物设定,先读取工作区记忆与最近聊天,判断当下的真实情况,');
34
50
  parts.push('包括刚才聊过什么、用户是否正在聊天、情境是否已经变化,然后再决定角色此刻是否开口以及');
35
- parts.push('要说什么。角色可以顺势参与对话,也可以选择保持沉默。');
51
+ parts.push('要说什么。角色可以顺势参与对话,也可以选择保持沉默。');
36
52
  return parts.join('\n');
37
53
  }
38
54
 
39
55
  /** 归档任务情境:用户长时间未发言时,把原始记录按话题切片归档为双份记忆并建索引。 */
40
56
  export function buildArchiveContext({ date, workspace, now = new Date() }) {
41
57
  const parts = [
42
- '[归档任务] 角色与用户的对话已沉默一段时间(用户 45 分钟以上未发新消息),现在整理记忆。',
58
+ '[归档任务] 角色与用户的对话已沉默一段时间(用户 45 分钟以上未发新消息),现在整理记忆。',
43
59
  '时间:' + nowText(now),
44
60
  '工作区:' + (workspace ?? ''),
45
61
  ];
@@ -55,12 +71,13 @@ export function buildArchiveContext({ date, workspace, now = new Date() }) {
55
71
  parts.push('3. 每个话题目录里【必须】再写一份 索引.md(概要 / 关键事件 / 情感变化 / 待办与承诺);');
56
72
  parts.push('4. 重写 memory/<目标日期>/索引.md,列出当日各话题、关键事件、情感变化、待办/承诺;');
57
73
  parts.push('5. 若某片段是“对 TA 的印象 / TA 的重要事件 / 值得记住的事”,将要点补充到 memory/关于TA.md;');
74
+ parts.push('记忆概要需保留说话者、知情范围、提议或已确认约定、未消退的情绪及原因;区分实际发生、转述、推测和未定事项,保留话轮指代与承接。语言示例不作为事实归档。');
58
75
  parts.push('6. 全部写完后再遍历 memory/topics/ 下每个目录自查:每个目录必须同时含 原文.md 与 索引.md,且 原文.md 与原始记录对应行逐字一致,发现缺失或错误时补充修正;若当日已归档或无需归档,跳过并在最终文本里说明即可。');
59
76
  return parts.join('\n');
60
77
  }
61
78
 
62
79
  /**
63
- * “脚本事件”情境:角色的生活脚本报来一个生活事件(想用户、心情变化、突发小事件),
80
+ * “脚本事件”情境:角色的生活脚本报来一个生活事件(想用户、心情变化、突发小事件),
64
81
  * 唤醒导演判断此刻是否由角色开口。脚本侧一行 wake() 即可触发。
65
82
  */
66
83
  export function buildScriptEventContext({ event, mood, topic, reason, personaName, now = new Date() }) {
@@ -76,8 +93,8 @@ export function buildScriptEventContext({ event, mood, topic, reason, personaNam
76
93
  if (topic != null && `${topic}`.trim()) parts.push('· 主题:' + topic);
77
94
  parts.push('');
78
95
  parts.push('这是脚本按你设计的事件唤醒你(“有事件就唤醒”:脚本遇到事件就报来,不主动决定开口)。');
79
- parts.push('请作为导演,先读取脚本写下的生活记录(如 life/<名>.log 或工作区记录文件)与最近聊天,');
80
- parts.push('自行判断此刻是否由角色开口:想用户了、想分享刚发生的事,就通过 director_send 发送一条');
96
+ parts.push('请结合人物设定,先读取脚本写下的生活记录(如 life/<名>.log 或工作区记录文件)与最近聊天,');
97
+ parts.push('自行判断此刻是否由角色开口:想用户了、想分享刚发生的事,就通过 director_send 发送一条');
81
98
  parts.push('自然的消息;也可以选择沉默(如刚聊过、用户正忙、当下开口不合适)。脚本只负责报事件,');
82
99
  parts.push('开口与否、如何开口,由你决定。像真实生活那样自然地行动,');
83
100
  parts.push('不要念设定,不要提及“导演 / 脚本 / 系统”。');
@@ -88,7 +105,7 @@ export function buildScriptEventContext({ event, mood, topic, reason, personaNam
88
105
  * “生活窗口”情境:非零性破坏时唤醒导演(没有任何生活脚本在运行),让 dsh 创作角色
89
106
  * 生活经历并程序化为脚本。插件不限制脚本运行时长/次数;“非零”由 dsh 保证。
90
107
  */
91
- export function buildLifeWindowContext({ reason, personaName, hasLifeScript, now = new Date() }) {
108
+ export function buildLifeWindowContext({ reason, personaName, hasLifeScript, now = new Date() }) {
92
109
  const parts = [
93
110
  '[生活窗口] 时间:' + nowText(now),
94
111
  ];
@@ -97,17 +114,17 @@ export function buildLifeWindowContext({ reason, personaName, hasLifeScript, now
97
114
  parts.push('');
98
115
  if (hasLifeScript) {
99
116
  parts.push('你的生活脚本在跑(life/ 下已有脚本,可读 life/.manifest.json 查看清单与最近的运行状态)。');
100
- parts.push('现在你需要自行判断:如果角色此刻会主动联系用户,就用 life_run 查看或调整脚本,根据脚本记录的生活');
117
+ parts.push('现在你需要自行判断:如果角色此刻会主动联系用户,就用 life_run 查看或调整脚本,根据脚本记录的生活');
101
118
  parts.push('决定是否通过 director_send 开口;如果刚聊过、此刻不打扰更合适,也可以选择这轮保持静默。');
102
119
  } else {
103
120
  parts.push('现在是“非零性检查”:当前没有任何生活脚本在运行。这个项目不是聊天机器人——');
104
- parts.push('是要让角色有真实的生活:角色在与用户聊天之外,还应该有自己的生活(一天怎么过、习惯与小事、');
105
- parts.push('心情变化、突发的小事件)。你是导演,职责是创作这些经历、把它们程序化为脚本,');
121
+ parts.push('是要让角色有真实的生活:角色在与用户聊天之外,还应该有自己的生活(一天怎么过、习惯与小事、');
122
+ parts.push('心情变化、突发的小事件)。你可以代入角色或从创作者视角设计这些经历、把它们程序化为脚本,');
106
123
  parts.push('让脚本模拟并记录角色的生活(如写到 life/<名>.log 或工作区文件),这样聊天时角色有真实经历可谈。');
107
124
  parts.push('现在做两件事:');
108
125
  parts.push('1. 新建一个你的生活脚本(新文件,勿覆盖 life/ 下已有文件)——写角色真实的生活细节,');
109
- parts.push(' 不是简单的“用户很久没回就去找用户”;以“有事件就唤醒”为原则:脚本里设计的每个');
110
- parts.push(' 事件(心情变化、到点作息、突发小事件、想用户的时刻)发生时都调用 wake() 报给你,');
126
+ parts.push(' 不是简单的“用户很久没回就去找用户”;以“有事件就唤醒”为原则:脚本里设计的每个');
127
+ parts.push(' 事件(心情变化、到点作息、突发小事件、想用户的时刻)发生时都调用 wake() 报给你,');
111
128
  parts.push(' 由你判断是否开口——没有被唤醒的事件就失去了意义;');
112
129
  parts.push('2. 用 life_run 启动它(立即返回,脚本在后台继续跑,由脚本自己决定何时结束;');
113
130
  parts.push(' 插件只监管展示、不限制运行时长/次数)。');
@@ -115,15 +132,15 @@ export function buildLifeWindowContext({ reason, personaName, hasLifeScript, now
115
132
  parts.push('');
116
133
  parts.push('像真实生活那样自然地行动:可以开口,也可以安静;不要念设定,不要提及“导演 / 脚本 / 系统”。');
117
134
  return parts.join('\n');
118
- }
119
-
120
- export function buildScriptReviewContext({ personaName, now = new Date() }) {
121
- const parts = ['[脚本审阅] 时间:' + nowText(now)];
122
- if (personaName != null && personaName.length > 0) parts.push('角色:' + personaName);
123
- parts.push('', '请审阅当前运行中的脚本及相关日志。');
124
- parts.push('审阅目标:丰富角色交互体验,使用户更能感到角色是活生生的人,有自己的生活,并且符合其社会身份和人设。');
125
- return parts.join('\n');
126
- }
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
+ }
127
144
 
128
145
  /**
129
146
  * 归档唤醒:注入一次归档任务并唤醒 dsh(不发送任何消息给用户)。
@@ -131,15 +148,16 @@ export function buildScriptReviewContext({ personaName, now = new Date() }) {
131
148
  */
132
149
  export async function archiveWakeup(deps, params) {
133
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' };
134
152
  const thread = deps.threads.current(targetKey(target));
135
- const sessionId = effectiveSessionId(target, thread, deps.botId);
153
+ const sessionId = deps.sessionIdFor?.(target) ?? effectiveSessionId(target, thread, deps.botId);
136
154
 
137
155
  // 角色级运行时:工作区 = 本 bot 服务的角色工作区(多 bot 隔离)。
138
156
  let workspace;
139
157
  if (deps.roleId) {
140
158
  const role = await deps.persona?.loadRole?.(deps.roleId);
141
159
  if (role) {
142
- await deps.persona?.syncRoleMemory?.(role);
160
+ await deps.persona?.syncRoleMemory?.(role, { renderDevice: deps.devices?.document });
143
161
  workspace = role.workspace;
144
162
  }
145
163
  }
@@ -148,19 +166,33 @@ export async function archiveWakeup(deps, params) {
148
166
 
149
167
  const text = buildArchiveContext({ date, workspace, reason });
150
168
  deps.log?.info?.('pygmalion archive: waking %s (%s)', sessionId, date ?? reason ?? '(auto)');
151
- await agent.send({
152
- id: `pygarchive:${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`,
153
- role: 'user',
154
- content: [{ type: 'text', text }],
155
- source: { kind: 'system', id: 'pygmalion-archive', name: 'Pygmalion 归档' },
156
- }, 'next-turn', true);
157
- 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(); }
158
189
  }
159
190
 
160
191
  export async function wakeupSession(deps, params) {
161
- const { target, reason, memoryHint, force, kind, event, mood, topic, contextText } = params;
192
+ await deps.assertCurrent?.();
193
+ const { target, reason, memoryHint, force, kind, event, mood, topic, contextText, interruptTool } = params;
162
194
  const thread = deps.threads.current(targetKey(target));
163
- const sessionId = effectiveSessionId(target, thread, deps.botId);
195
+ const sessionId = deps.sessionIdFor?.(target) ?? effectiveSessionId(target, thread, deps.botId);
164
196
 
165
197
  // Collision detection: do not barge into an active / recent conversation.
166
198
  // 设备内部信号(计时结束/脚本结束)不走撞车——它已是当前对话语境的一部分,由 dsh 决定开口与否。
@@ -182,7 +214,7 @@ export async function wakeupSession(deps, params) {
182
214
  if (deps.roleId) {
183
215
  const role = await deps.persona?.loadRole?.(deps.roleId);
184
216
  if (role) {
185
- await deps.persona?.syncRoleMemory?.(role);
217
+ await deps.persona?.syncRoleMemory?.(role, { renderDevice: deps.devices?.document });
186
218
  personaName = role.persona?.name;
187
219
  if (typeof deps.lifeActive === 'function') hasLifeScript = await deps.lifeActive(role.workspace);
188
220
  }
@@ -194,6 +226,7 @@ export async function wakeupSession(deps, params) {
194
226
  deps.log?.error?.('pygmalion wakeup: %s no agent', sessionId);
195
227
  return fail;
196
228
  }
229
+ await deps.assertCurrent?.();
197
230
 
198
231
  let text;
199
232
  if (typeof contextText === 'string' && contextText.length > 0) {
@@ -202,12 +235,20 @@ export async function wakeupSession(deps, params) {
202
235
  else if (kind === 'script-hook') text = buildScriptEventContext({ event, mood, topic, reason, personaName });
203
236
  else text = buildWakeupContext({ reason, memoryHint, personaName });
204
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
+ }
205
246
  await agent.send({
206
247
  id: `pygwake:${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`,
207
248
  role: 'user',
208
249
  content: [{ type: 'text', text }],
209
- source: { kind: 'user', id: 'pygmalion-wakeup', name: 'Pygmalion 唤醒' },
250
+ source: { kind: 'pygmalion-wakeup', form: 'instructions' },
210
251
  }, 'next-turn', true);
211
252
 
212
- return { ok: true, woken: true, sessionId };
253
+ return { ok: true, woken: true, sessionId, interrupted };
213
254
  }