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/tools.js CHANGED
@@ -1,17 +1,22 @@
1
1
  import { targetOfSession, SESSION_PREFIX } from './inbound.js';
2
2
  import { readdir, readFile } from 'node:fs/promises';
3
3
  import { existsSync } from 'node:fs';
4
- import { join } from 'node:path';
5
- import { TOY_REFERENCE_NAME } from './devices/manager.mjs';
4
+ import { join } from 'node:path';
5
+ import { TOY_REFERENCE_NAME } from './devices/manager.mjs';
6
6
  import { findLifeScript, listLifeScripts, startLifeScript, stopLifeScript, readLifeManifest, snapshotLifeScript } from './agent-life.js';
7
- import { sessionFileFor } from './active-session.js';
8
7
  import { refreshRawRecordFromSession, charLabelOf } from './memory-write.js';
8
+ import { recallMemory } from './memory-recall.js';
9
9
  import { saveMeme, findMemes, memeFileFor, updateMeme, recordMemeUsed, downloadPageImagesToCollectDir } from './memebox.js';
10
- import { resolveVisionConfig, collectAndClassify, withMemeLock, readImageBySubagent, archiveImageBySubagent, memeTrace } from './meme-worker.js';
11
- import { synthesizeMiMoVoice } from './voice-mimo.js';
10
+ import { resolveVisionConfig, collectAndClassify, withMemeLock, readImageBySubagent, archiveImageBySubagent, memeTrace } from './meme-worker.js';
11
+ import { isVoiceSynthesisTimeout } from './voice.js';
12
+ import { normalizeDirectorMessages, validateDirectorMessages } from './director-messages.js';
13
+ import { deliveryReceiptSchema, deliveryMeta } from './delivery-receipt.js';
14
+ import { matchesRoleTarget } from './peer-identity.js';
12
15
 
13
16
  const IMAGE_EXTS = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.svg', '.ico']);
14
17
  const VOICE_EXTS = new Set(['.wav', '.mp3', '.silk', '.amr', '.ogg', '.flac', '.aac', '.m4a']);
18
+ /** sessionId → 最近一次因参数校验退回而保留的 reawake.id;重试时精确替换,避免队列堆积。 */
19
+ const rejectedReawakeBySession = new Map();
15
20
 
16
21
  /** dsh 工具输出要求无损 JSON(拒绝 undefined/NaN/非有限数);返回前剥掉 undefined 字段。 */
17
22
  function noUndefined(obj) {
@@ -71,9 +76,9 @@ export function buildQQToolDefs(resolveCtx) {
71
76
  return [
72
77
  {
73
78
  name: 'qq_send_media',
74
- description: 'Send an image, voice, video, or file message to the current QQ chat. '
79
+ description: 'Send media supported by the current chat connection. '
75
80
  + 'Accepts an https URL, a data: URL, or an absolute local file path '
76
- + '(files larger than 10MB upload through the chunked pipeline automatically). '
81
+ + '(encoding and upload limits are defined by the connection). '
77
82
  + 'Use this instead of pasting image URLs as text when the user asks for a media message.',
78
83
  parameters: {
79
84
  type: 'object',
@@ -167,52 +172,50 @@ export function buildDirectorToolDefs(resolveCtx) {
167
172
  // director_send:向当前 QQ 用户发送聊天消息(导演模式的唯一发送通道)。
168
173
  {
169
174
  name: 'director_send',
170
- description: '让角色向当前 QQ 用户发送聊天消息(本模式的唯一发送通道)。QQ 用户在与角色交流,不是在与导演交流。'
171
- + 'messages 为一次下发的 1~N 个独立 QQ 消息气泡。普通文字通常一条只写一句自然口语或一个很小的意思,'
172
- + '句末往往不加句号;需要连续表达时才按真人的聊天节奏拆成数条,不写大段文章、markdown、动作描写、心理旁白或括号情绪标签。'
173
- + '【reawake 是默认动作】发送消息时,几乎每一次都应该同时带上 reawake 参数。'
174
- + 'reawake 填一个正数,表示多少分钟后若用户没有回复,系统会在到点唤醒你继续这段对话;'
175
+ description: '向当前聊天对象提交角色真正要说的消息(本模式的唯一发送通道)。'
176
+ + 'messages 每项是一条文字或语音消息。表达风格、标点、语气词及分条习惯,按当前人物设定与场景决定。'
177
+ + '普通文字不包含幕后分析、心理旁白、舞台说明或括号情绪标签。'
178
+ + '【reawake 是默认动作】发送消息时,几乎每一次都应该同时带上 reawake 参数。'
179
+ + 'reawake 填一个正数,表示多少分钟后若用户没有回复,系统会在到点唤醒你重新审视情境;'
175
180
  + '填 "none" 或省略则表示不安排。这是维持主动联系、不让关系冷掉的机制,不安排就意味着'
176
- + '这轮聊完之后你将一直静默等待用户。reawake 的分钟数应当根据当下的具体情景灵活决定,'
177
- + '不要套用固定的区间:如果角色与用户正聊到一半、话题还没有结束,或者角色不会在此结束这次聊天,'
178
- + '就填一个较短的间隔,比如 3 到 10 分钟;如果角色与用户约定了某个具体的时刻再继续,比如'
179
- + '“中午再聊”,就把分钟数直接算到那个时刻,距离中午还有 3 个小时就填 180;如果只是平时'
180
- + '自然地把话题搁一搁,填一个适中的间隔即可。'
181
- + 'messages 为空数组时可只安排 reawake 而本次不发。'
182
- + '只允许发送拟真的、贴合角色性格的聊天文本;绝不发送思考、计划、动作描述、工具说明或任何非消息内容。'
183
- + '文本与语音须像真人使用 QQ 那样随情景自然选择,既不能每条都发语音,也不能长期完全不用语音。'
184
- + '语音项的 text 是原样朗读的台词;scene 写清当前事件、对象和人物动机;direction 只给一句整段成立的表演意图。'
185
- + '角色音色身份已经由管理页配置,不要在语音项重复。禁止用“前面/中段/后面”等模糊时序词、逐句声学控制、旁白或台词外心理活动。'
186
- + '仅语音 text 可在必要处加入少量简短的中文圆括号语义标签,如“(轻笑)”“(压低声音)”“(停顿)”,供语音模型控制表演;'
187
- + '不把场景、心理活动或长指令塞进标签,也不用标签编排逐句变化。'
188
- + '如果你决定此刻不打扰对方,就不要调用本工具。',
181
+ + '这轮聊完之后你将一直静默等待用户。时长应符合真实生活,考虑用户可能离开手机、双方正在做的事、明确约定、'
182
+ + '届时情境是否可能变化以及连续没有回复后自然延长的等待,不套用固定区间。reason 只记录届时重新观察的情况,'
183
+ + '不预写下一条消息,也不预设醒来后一定开口。'
184
+ + 'messages 为空数组时可只安排 reawake 而本次不发。'
185
+ + '只允许发送拟真的、贴合角色性格的聊天文本;绝不发送思考、计划、动作描述、工具说明或任何非消息内容。'
186
+ + '文本与语音须像真人聊天 那样随情景自然选择,既不能每条都发语音,也不能长期完全不用语音。'
187
+ + '语音项的 text 是原样朗读的台词;scene 写清当前事件、对象和人物动机;direction 只给一句整段成立的表演意图。'
188
+ + '语音合成按台词长度设置等待时限;若超时,系统会自动把同一台词作为文字发送,并在工具结果中明确说明。'
189
+ + '角色音色身份已经由管理页配置,不要在语音项重复。禁止用“前面/中段/后面”等模糊时序词、逐句声学控制、旁白或台词外心理活动。'
190
+ + '仅当当前语音能力明确支持括号表演标签时,语音 text 才可少量使用简短标签;否则台词只包含真正朗读的文字。'
191
+ + '不把场景、心理活动或长指令塞进标签,也不用标签编排逐句变化。'
192
+ + '如果你决定此刻不打扰对方,就不要调用本工具。',
189
193
  parameters: {
190
194
  type: 'object',
191
195
  additionalProperties: false,
192
196
  properties: {
193
- messages: {
194
- type: 'array',
195
- items: { oneOf: [
196
- { type: 'string' },
197
- { type: 'object', additionalProperties: false, required: ['type', 'text'], properties: {
198
- type: { type: 'string', enum: ['text', 'voice'] },
199
- text: { type: 'string', description: '普通文字的发送内容,或 voice 的朗读台词。普通文字不使用括号情绪/动作标签;仅语音台词可用少量简短圆括号语义标签控制表演,如“(轻笑)”。' },
200
- scene: { type: 'string', description: '仅 voice:本条语音的完整情景、对话对象与情绪动机;不要重复管理页角色设定。' },
201
- direction: { type: 'string', description: '仅 voice:一句整体表演方向;不编排逐句变化时机,不写模糊时序词或旁白。语音表演所需的简短语义标签放在 voice 的 text 中。' },
202
- } },
203
- ] },
204
- description: '按顺序发送的消息;字符串兼容旧文本格式。voice 由角色已配置的 MiMo 音色合成并发送。空数组或省略 = 不发送。',
197
+ messages: {
198
+ type: 'array',
199
+ items: { oneOf: [
200
+ { type: 'string' },
201
+ { type: 'object', additionalProperties: false, required: ['type', 'text'], properties: {
202
+ type: { type: 'string', enum: ['text', 'voice'] },
203
+ text: { type: 'string', description: '普通文字的发送内容,或 voice 真正朗读的台词。括号表演标签仅在当前语音能力明确支持时可用。' },
204
+ scene: { type: 'string', description: '仅 voice:本条语音的完整情景、对话对象与情绪动机;不要重复管理页角色设定。' },
205
+ direction: { type: 'string', description: '仅 voice:一句整体表演方向;不编排逐句变化时机,不写模糊时序词或旁白。语音表演所需的简短语义标签放在 voice 的 text 中。' },
206
+ } },
207
+ ] },
208
+ description: '按顺序发送的消息;字符串兼容旧文本格式。voice 由角色所选语音服务合成并发送。空数组或省略 = 不发送。',
205
209
  },
206
210
  reawake: {
207
211
  oneOf: [{ type: 'number' }, { type: 'string' }],
208
- description: '建议默认携带。具体的分钟数根据当下的情景决定:如果话题还没有结束,'
209
- + '填一个较短的间隔,比如 3 到 10 分钟;如果约定了某个具体的时刻再继续,就填到那个时刻的分钟数,'
210
- + '比如约好中午再聊、距离中午还有 3 个小时,就填 180;平时自然搁置则填一个适中的间隔。'
212
+ description: '建议默认携带。具体分钟数须按真实情境决定:考虑用户可能离开手机、双方正在做的事、明确约定、'
213
+ + '届时情境是否可能变化,以及连续没有回复后自然延长的等待;不要套用固定区间。'
211
214
  + '填正数会登记等待队列;明确决定这轮不再续聊时才写 "none" 或省略。',
212
215
  },
213
216
  reason: {
214
217
  type: 'string',
215
- description: '可选:reawake 到期时唤醒导演的缘由(角色届时可能继续说的话或想确认的事)。',
218
+ description: '可选:reawake 到期时需要重新观察的情境线索。不要预写下一条消息,也不要预设届时一定开口。',
216
219
  },
217
220
  },
218
221
  },
@@ -220,81 +223,146 @@ export function buildDirectorToolDefs(resolveCtx) {
220
223
  schema: {
221
224
  type: 'object',
222
225
  additionalProperties: false,
223
- properties: { ok: { type: 'boolean' }, sent: { type: 'number' }, textSent: { type: 'number' }, voiceSent: { type: 'number' }, failedAt: { type: 'number' }, reawake: { type: 'number' }, error: { type: 'string' } },
226
+ properties: {
227
+ ok: { type: 'boolean' }, sent: { type: 'number' }, textSent: { type: 'number' }, voiceSent: { type: 'number' },
228
+ voiceTimeouts: { type: 'array', items: { type: 'number' } },
229
+ delivery: deliveryReceiptSchema,
230
+ failedAt: { type: 'number' }, reawake: { type: 'number' }, error: { type: 'string' },
231
+ },
224
232
  required: ['ok', 'sent'],
225
233
  },
226
- render: (_args, value) => [
227
- { type: 'text', text: value.ok
228
- ? `已发送 ${value.sent} 条消息${value.reawake ? `,已安排 ${value.reawake} 延时唤醒` : ''}`
229
- : `发送失败: ${value.error ?? '?'}` },
230
- ],
234
+ presentationMeta: deliveryMeta,
235
+ render: (_args, value) => {
236
+ const timedOut = Array.isArray(value.voiceTimeouts) ? value.voiceTimeouts : [];
237
+ const timeoutText = timedOut.length > 0
238
+ ? `(第 ${timedOut.join('、')} 条语音合成超时,已自动改发文字)`
239
+ : '';
240
+ return [{ type: 'text', text: value.ok
241
+ ? `已发送 ${value.sent} 条消息${timeoutText}${value.reawake ? `,已安排 ${value.reawake} 延时唤醒` : ''}`
242
+ : `发送失败: ${value.error ?? '?'}${value.sent > 0 ? `(失败前已发送 ${value.sent} 条消息)` : ''}`
243
+ + timeoutText + `${value.reawake ? '(有效的延时唤醒已保留)' : ''}` }];
244
+ },
231
245
  },
232
- timeoutMs: 360_000,
246
+ timeoutMs: 360_000,
233
247
  async execute(args, exec) {
234
248
  const c = await resolveCtx(args, exec);
235
- const raw = Array.isArray(args?.messages) ? args.messages : [];
236
- const messages = raw.map((item) => typeof item === 'string'
237
- ? { type: 'text', text: item.trim() }
238
- : { type: item?.type === 'voice' ? 'voice' : 'text', text: String(item?.text ?? '').trim(), scene: String(item?.scene ?? '').trim(), direction: String(item?.direction ?? '').trim() })
239
- .filter((item) => item.text.length > 0);
240
- const sent = [];
249
+ const raw = Array.isArray(args?.messages) ? args.messages : [];
250
+ const messages = normalizeDirectorMessages(raw);
251
+ const target = c.target();
252
+ let attempt;
253
+ try {
254
+ attempt = await c.beginDelivery?.(target, exec?.signal);
255
+ } catch (error) {
256
+ return { ok: false, sent: 0, error: error.message };
257
+ }
258
+ const signal = attempt?.signal ?? exec?.signal;
259
+ const check = async () => { signal?.throwIfAborted(); await attempt?.assertCurrent(); };
260
+ // 有效的 reawake 先登记。即使候选消息随后被参数校验退回,关系仍有
261
+ // 下一次继续的可能;dsh 在当前轮重试时会用新安排覆盖它。
262
+ const ra = args?.reawake;
263
+ let reawakeAt;
264
+ let scheduledReawakeId;
265
+ if (ra !== undefined && ra !== null && ra !== 'none' && ra !== 'NONE') {
266
+ const minutes = typeof ra === 'number' ? ra : Number(String(ra).trim());
267
+ if (!Number.isFinite(minutes) || minutes <= 0)
268
+ return { ok: false, sent: 0, error: 'reawake 必须是正数分钟、"none" 或省略' };
269
+ const replaceId = rejectedReawakeBySession.get(c.sessionId);
270
+ const rw = c.roleId && c.persona?.scheduleRewake
271
+ ? await c.persona.scheduleRewake(c.roleId, minutes, typeof args?.reason === 'string' ? args.reason : '',
272
+ replaceId === undefined ? {} : { replaceId })
273
+ : { ok: false, atMs: 0, error: '无角色上下文' };
274
+ if (!rw.ok) return { ok: false, sent: 0, error: `reawake 安排失败: ${rw.error ?? '?'}` };
275
+ reawakeAt = rw.atMs;
276
+ rejectedReawakeBySession.delete(c.sessionId);
277
+ // 只有随后确实退回时才重新放入 map;正常发送保留原有“多个独立等待可并存”语义。
278
+ scheduledReawakeId = rw.id;
279
+ }
280
+ const withReawake = (value) => reawakeAt ? { ...value, reawake: reawakeAt } : value;
281
+ const hardIssues = validateDirectorMessages(raw, messages);
282
+ if (hardIssues.length > 0) {
283
+ if (scheduledReawakeId !== undefined) rejectedReawakeBySession.set(c.sessionId, scheduledReawakeId);
284
+ return withReawake({ ok: false, sent: 0, error: `消息未发送:${hardIssues.join(';')}` });
285
+ }
286
+
287
+ const sent = [];
288
+ const deliveredTypes = [];
289
+ const voiceTimeouts = [];
290
+ const delivery = { version: 1, messages: [] };
241
291
  if (messages.length > 0) {
242
- const record = c.routes?.get(c.sessionId);
243
- const passive = record
244
- ? c.routes.consumePassive(c.sessionId, record.target.kind === 'group' ? 5 * 60 * 1000 : 30 * 60 * 1000, 4)
245
- : undefined;
246
- for (const msg of messages) {
247
- try {
248
- if (msg.type === 'voice') {
249
- if (!c.roleId) throw new Error('当前会话没有角色语音配置');
250
- const audio = await synthesizeMiMoVoice({ roleId: c.roleId, text: msg.text, scene: msg.scene, direction: msg.direction });
251
- try { await c.api.sendMedia(c.target(), 'voice', audio.file, { passiveMsgId: passive }); }
252
- finally { await audio.cleanup(); }
253
- } else {
254
- await c.api.sendText(c.target(), msg.text, passive);
255
- }
256
- sent.push(msg);
292
+ const passive = c.api.replyContext?.(c.sessionId);
293
+ for (let messageIndex = 0; messageIndex < messages.length; messageIndex++) {
294
+ const msg = messages[messageIndex];
295
+ let submitted = false, actualType = msg.type;
296
+ try {
297
+ await check();
298
+ if (msg.type === 'voice') {
299
+ if (c.api.supportsMedia?.('voice') === false) throw new Error('当前通信实现不支持语音消息');
300
+ if (!c.roleId) throw new Error('当前会话没有角色语音配置');
301
+ const synthesizeVoice = c.synthesizeVoice ?? c.voice?.synthesize;
302
+ if (typeof synthesizeVoice !== 'function') throw new Error('角色语音服务不可用');
303
+ let audio;
304
+ try {
305
+ audio = await synthesizeVoice({ roleId: c.roleId, text: msg.text, scene: msg.scene,
306
+ direction: msg.direction, signal });
307
+ } catch (error) {
308
+ if (!isVoiceSynthesisTimeout(error)) throw error;
309
+ await check();
310
+ actualType = 'text'; submitted = true;
311
+ await c.api.sendText(target, msg.text, passive);
312
+ voiceTimeouts.push(messageIndex + 1);
313
+ deliveredTypes.push('text');
314
+ }
315
+ if (audio) {
316
+ try {
317
+ await check();
318
+ await audio.assertCurrent?.();
319
+ submitted = true;
320
+ await c.api.sendMedia(target, 'voice', audio.file, { passiveMsgId: passive });
321
+ } finally {
322
+ try { await audio.cleanup?.(); }
323
+ catch { c.log?.warn?.('语音临时产物清理失败;发送结果保持不变'); }
324
+ }
325
+ deliveredTypes.push('voice');
326
+ }
327
+ } else {
328
+ submitted = true;
329
+ await c.api.sendText(target, msg.text, passive);
330
+ deliveredTypes.push('text');
331
+ }
332
+ sent.push(msg);
333
+ delivery.messages.push({ index: messageIndex, type: deliveredTypes.at(-1), status: 'accepted' });
257
334
  }
258
335
  catch (error) {
259
- return {
260
- ok: false, sent: sent.length, failedAt: sent.length,
336
+ delivery.messages.push({ index: messageIndex, type: actualType, status: submitted ? 'unknown' : 'failed' });
337
+ return withReawake({
338
+ ok: false, sent: sent.length, failedAt: sent.length,
339
+ voiceTimeouts, delivery,
261
340
  error: error instanceof Error ? error.message : String(error),
262
- };
341
+ });
263
342
  }
264
343
  }
265
344
  // 日期层记忆:角色消息发出后延迟从活跃会话 session log 提取写原始记录
266
345
  // (等 dsh 把 director_send 工具调用落盘;仅 c2c 拥有者会话)。
267
- if (sent.length > 0 && c.target()?.kind === 'c2c') {
346
+ if (sent.length > 0 && matchesRoleTarget(await c.persona?.loadRole?.(c.roleId), c.target(), c.identityScope)) {
268
347
  const workspace = c.workspaceOf
269
348
  ? await c.workspaceOf()
270
349
  : (c.persona && c.roleId ? c.persona.roleWorkspace(c.roleId) : undefined);
271
350
  if (workspace && c.sessionId) {
272
- const file = sessionFileFor({ sessionId: c.sessionId, workspace });
273
351
  // 会话文件不存在则无内容可提取(测试/调试 stub 路径跳过,避免挂空定时器)。
274
- if (existsSync(file)) {
352
+ if (c.sessionPersistence) {
275
353
  const charLabel = c.roleId && c.persona ? await charLabelOf(c.persona, c.roleId) : '角色';
276
354
  setTimeout(() => {
277
- void refreshRawRecordFromSession({ workspace, sessionFile: file, charLabel, log: c.log })
355
+ void refreshRawRecordFromSession({ workspace, sessionId: c.sessionId, persistence: c.sessionPersistence, charLabel, log: c.log })
278
356
  .catch((error) => c.log?.warn?.('pygmalion: 刷新原始记录失败: %o', error));
279
357
  }, 3000);
280
358
  }
281
359
  }
282
360
  }
283
361
  }
284
- // reawake:正数分钟 → 写角色 state.rewake 队列;'none'/缺省 → 不安排。
285
- const ra = args?.reawake;
286
- if (ra === undefined || ra === null || ra === 'none' || ra === 'NONE')
287
- return { ok: true, sent: sent.length, textSent: sent.filter((m) => m.type === 'text').length, voiceSent: sent.filter((m) => m.type === 'voice').length };
288
- const minutes = typeof ra === 'number' ? ra : Number(String(ra).trim());
289
- if (Number.isFinite(minutes) && minutes > 0) {
290
- const rw = c.roleId && c.persona?.scheduleRewake
291
- ? await c.persona.scheduleRewake(c.roleId, minutes, typeof args?.reason === 'string' ? args.reason : '')
292
- : { ok: false, atMs: 0, error: '无角色上下文' };
293
- if (!rw.ok)
294
- return { ok: false, sent: sent.length, error: `reawake 安排失败: ${rw.error ?? '?'}` };
295
- return { ok: true, sent: sent.length, reawake: rw.atMs };
296
- }
297
- return { ok: true, sent: sent.length };
362
+ return withReawake({ ok: true, sent: sent.length,
363
+ textSent: deliveredTypes.filter((type) => type === 'text').length,
364
+ voiceSent: deliveredTypes.filter((type) => type === 'voice').length,
365
+ voiceTimeouts, delivery });
298
366
  },
299
367
  },
300
368
  // recollect:按需回忆(只在需要回忆/找话题时调用)
@@ -321,7 +389,7 @@ export function buildDirectorToolDefs(resolveCtx) {
321
389
  required: ['found', 'text'],
322
390
  },
323
391
  render: (_args, value) => [
324
- { type: 'text', text: value.found ? `[回忆]\n${String(value.text).slice(0, 4000)}` : '(记忆中没有相关内容)' },
392
+ { type: 'text', text: value.found ? `[回忆]\n${String(value.text)}` : '(记忆中没有相关内容)' },
325
393
  ],
326
394
  },
327
395
  timeoutMs: 20_000,
@@ -329,49 +397,7 @@ export function buildDirectorToolDefs(resolveCtx) {
329
397
  const c = await resolveCtx(args, exec);
330
398
  const ws = typeof c.workspaceOf === 'function' ? await c.workspaceOf() : null;
331
399
  if (!ws) return { found: false, text: '' };
332
- const mem = join(ws, 'memory');
333
- const out = [];
334
- // 特殊记忆:对 TA 的印象/重要事件(dsh 直接编辑);空白模板不返回。
335
- try {
336
- const aboutUser = (await readFile(join(mem, '关于TA.md'), 'utf8')).trim();
337
- if (aboutUser && aboutUser !== '(空白,等待你记录对 TA 的了解)')
338
- out.push(`== 关于TA(特殊记忆)==\n${aboutUser.slice(0, 2000)}`);
339
- } catch { /* 尚无特殊记忆 */ }
340
- // 话题层:topics/<话题>[YYYY-MM-DD HH:MM:SS-YYYY-MM-DD HH:MM:SS]/索引.md
341
- try {
342
- const subs = (await readdir(join(mem, 'topics'))).filter((n) => !n.startsWith('.')).sort().reverse();
343
- for (const name of subs.slice(0, 20)) {
344
- try {
345
- const ti = await readFile(join(mem, 'topics', name, '索引.md'), 'utf8');
346
- out.push(`== 话题 ${name} ==\n${ti.slice(0, 1200)}`);
347
- } catch { /* 该话题无索引 */ }
348
- }
349
- } catch { /* 无话题层 */ }
350
- // 日期层:索引(默认最近 N 天;指定日期则附当日原文片段)
351
- let dates = [];
352
- try { dates = (await readdir(mem)).filter((n) => /^\d{4}-\d{2}-\d{2}$/.test(n)).sort().reverse(); } catch { /* no memory yet */ }
353
- if (dates.length) {
354
- const limit = Math.min(Math.max(Number(args?.limit) || 3, 1), 10);
355
- const pick = args?.date ? [String(args.date)] : dates.slice(0, limit);
356
- for (const d of pick) {
357
- const idx = join(mem, d, '索引.md');
358
- const raw = join(mem, d, '原始记录.md');
359
- try {
360
- let t = `== ${d} 索引 ==\n` + await readFile(idx, 'utf8');
361
- if (args?.date && args.date === d) {
362
- try { t += `\n== ${d} 原文(片段) ==\n` + (await readFile(raw, 'utf8')).slice(0, 2000); } catch { /* 无原文 */ }
363
- }
364
- out.push(t);
365
- } catch { /* 该日无索引 */ }
366
- }
367
- }
368
- let text = out.join('\n\n');
369
- if (args?.topic) {
370
- const q = String(args.topic).toLowerCase();
371
- const filtered = text.split('\n').filter((l) => l.toLowerCase().includes(q));
372
- text = filtered.length ? filtered.join('\n') : text;
373
- }
374
- return text.trim() ? { found: true, text: text.trim().slice(0, 6000) } : { found: false, text: '' };
400
+ return recallMemory(ws, args);
375
401
  },
376
402
  },
377
403
  // life_run:在插件监管下启动/终止角色生活脚本(dsh 全权决定运行,插件只监管展示)
@@ -380,17 +406,18 @@ export function buildDirectorToolDefs(resolveCtx) {
380
406
  description: '启动你在 life/ 下写的角色生活脚本(.mjs/.js/.py/.ts,可指定文件名)。'
381
407
  + '脚本是“角色生活的程序化模拟器”:由你创作角色在聊天之外的经历并程序化(一天的节奏、'
382
408
  + '习惯、社交、心情变化、突发小事件),把经历写成可读记录(如 life/<名>.log 或工作区文件),'
383
- + '这样角色有自己的生活,聊天时有真实经历可谈——而不是简单的“用户很久没回就去找用户”。'
409
+ + '这样角色有自己的生活,聊天时有真实经历可谈——而不是简单的“用户很久没回就去找用户”。'
384
410
  + '脚本何时运行、怎么写、何时结束完全由你决定:可以长驻循环(while/setInterval),结束条件'
385
411
  + '写在脚本里;插件不限制运行时长/次数,只登记运行状态、把输出写进 life/.logs/,并在管理页'
386
412
  + '展示脚本内容与运行日志(受监管)。启动立即返回 runId/pid,脚本在后台继续跑;'
387
413
  + '要终止用 stop=<runId>。'
388
414
  + '脚本以“有事件就唤醒”为设计原则:脚本里设计的每个生活事件(心情变化、到点作息、'
389
- + '突发小事件、想用户的时刻)在发生时都调用 wake({ mood, topic, reason, force }) —— node '
415
+ + '突发小事件、想用户的时刻)在发生时都调用 wake({ mood, topic, reason, force }) —— node '
390
416
  + '脚本启动时已自动预加载全局 wake(),直接调用即可(无需 import / fetch / 网络):内部经'
391
417
  + 'HTTP 调插件 /wakeup 端点,插件节流(默认同角色 10 分钟内至多一次)+ 撞车检测后'
392
418
  + '唤醒 dsh 注入 [脚本事件] 情境;是否开口、如何开口由你(导演)被唤醒后自行判断'
393
- + '(可以选择沉默)——没有被唤醒的事件就失去了意义。'
419
+ + '(可以选择沉默)。wake() 的意义是让事件成为导演已经知晓的角色经历;事件被知晓后目的已经达成,'
420
+ + '是否把它转化成 QQ 消息是另一项独立判断。'
394
421
  + '重要:唤醒消息里只包含 wake() 参数中的文本(mood/topic/reason 会注入 [脚本事件]'
395
422
  + '情境);脚本其它任何输出(console.log、写日志/日记文件等)都不会进入唤醒消息——'
396
423
  + '想让导演在唤醒时看到的情境,必须写进 wake() 参数,否则对唤醒毫无意义。'
@@ -467,6 +494,7 @@ export function buildDirectorToolDefs(resolveCtx) {
467
494
  token: c.httpApiToken,
468
495
  httpApiPath: c.httpApiPath,
469
496
  openid: role?.binding?.openid,
497
+ roleScopedHook: c.target()?.kind === 'direct',
470
498
  });
471
499
  return res.ok
472
500
  ? { ok: true, runId: res.runId, pid: res.pid, startedAt: res.startedAt, script: res.script }
@@ -476,7 +504,7 @@ export function buildDirectorToolDefs(resolveCtx) {
476
504
  // toy_status:查询角色可用设备状态
477
505
  {
478
506
  name: 'toy_status',
479
- description: '查询当前角色已授权可用设备的状态:是否已激活(用户是否发过分享链接)、当前运行状态'
507
+ description: '查询当前角色已授权可用设备的状态:是否已激活(用户是否发过分享链接)、当前运行状态'
480
508
  + '(controller/last 参数/是否有脚本在跑)。需要操作设备前可先调用确认。',
481
509
  parameters: {
482
510
  type: 'object',
@@ -500,7 +528,7 @@ export function buildDirectorToolDefs(resolveCtx) {
500
528
  if (!v?.ok) text = `toy_status 失败: ${v?.error ?? '?'}`;
501
529
  else if (!v.devices?.length) text = '该角色未配置可用设备。';
502
530
  else {
503
- const lines = v.devices.map((d) => `- ${d.alias}(${d.kind}):${d.activated ? '已激活' : '未激活——需用户发分享链接'}`
531
+ const lines = v.devices.map((d) => `- ${d.alias}(${d.kind}):${d.activated ? '已激活' : '未激活——需用户发分享链接'}`
504
532
  + (d.activated ? ` | 运行:${d.controller}${d.last ? ` 参数=${d.last.intensity !== 0 || d.last.stroke ? JSON.stringify(d.last) : ''}` : ''}${d.runId ? ` | 脚本=${d.runId}` : ''}` : ''));
505
533
  text = ['可用设备:'].concat(lines).join('\n');
506
534
  }
@@ -512,18 +540,19 @@ export function buildDirectorToolDefs(resolveCtx) {
512
540
  const c = await resolveCtx(_args, exec);
513
541
  if (!c.devices) return { ok: false, error: '设备服务不可用' };
514
542
  if (!c.roleId) return { ok: false, error: '无角色上下文' };
515
- return await c.devices.status(c.roleId);
543
+ return await (c.devices.monsterpartyStatus?.(c.roleId) ?? c.devices.status(c.roleId));
516
544
  },
517
545
  },
518
546
  // toy_control:定时/即时操控设备(工具调用模式)
519
547
  {
520
548
  name: 'toy_control',
521
- description: '操控当前角色可用的玩具设备(行程+强度)。需要用户已发过一条新鲜分享链接(激活),否则会提示先请用户发。\n'
549
+ description: '操控当前角色可用的玩具设备(行程+强度)。需要用户已发过一条新鲜分享链接(激活),否则会提示先请用户发。\n'
522
550
  + '参数:intensity 强度 0-100;stroke 行程范围(用两个边界,取值 0/33/66/100,如 "0,100"=L1~L3 全行程往复、'
523
551
  + '"0,66"=L1~L2 区间、"0,0"=停住;也可写区间名 "L1,L2");seconds 本次操作的时长(秒)。\n'
524
552
  + '计时语义:到点后设备保持当前参数继续运行,系统会提醒你计时结束,可再次调用本工具调整或 stop。'
525
- + '设备无自动停止——由你决定何时停(用户要求停时必须停);停用 stop:true。\n'
526
- + '注意:新一次调用会接管当前计时/脚本;单台设备一次只有一个在跑。',
553
+ + '设备无自动停止——由你决定何时停(用户要求停时必须停);停用 stop:true。\n'
554
+ + '注意:玩具脚本运行期间,除 stop:true 外本工具不会接管控制。若要改用 toy_control 操控,必须先显式停止正在运行的脚本:'
555
+ + '调用 toy_run_script 的 stop=<runId>(或单独调用 toy_control stop:true 停止脚本和设备),确认停止后再发起新的 toy_control 控制。',
527
556
  parameters: {
528
557
  type: 'object',
529
558
  additionalProperties: false,
@@ -552,7 +581,7 @@ export function buildDirectorToolDefs(resolveCtx) {
552
581
  let text;
553
582
  if (!v?.ok) {
554
583
  const err = v?.error ?? '?';
555
- text = `toy_control 失败: ${err}${err.includes('激活') || err.includes('分享链接') ? '(让用户发一条新鲜分享链接即可)' : ''}`;
584
+ text = `toy_control 失败: ${err}${err.includes('激活') || err.includes('分享链接') ? '(让用户发一条新鲜分享链接即可)' : ''}`;
556
585
  } else {
557
586
  const s = v.state;
558
587
  const last = s?.last;
@@ -587,17 +616,19 @@ export function buildDirectorToolDefs(resolveCtx) {
587
616
  return noUndefined(out);
588
617
  },
589
618
  },
590
- // toy_run_script:运行玩具操控脚本
619
+ // toy_run_script:运行玩具操控脚本
591
620
  {
592
621
  name: 'toy_run_script',
593
- description: '运行你在 workspace/toys/ 下写的一个设备操控脚本(.mjs/.js/.ts)。应使用脚本构建玩具运动的“波形”来控制玩具:不是随机抽取参数,也不是把若干参数和固定时长简单串成阶段表;具体波形由你自行设计。编写或运行前必须先读取 workspace/toys/玩具脚本示例.mjs。\n'
622
+ description: '运行你在 workspace/toys/ 下写的一个设备操控脚本(.mjs/.js/.ts)。应使用脚本构建玩具运动的“波形”来控制玩具:不是随机抽取参数,也不是把若干参数和固定时长简单串成阶段表;具体波形由你自行设计。编写或运行前必须先读取 workspace/toys/玩具脚本示例.mjs。\n'
594
623
  + '脚本侧只需关心设备参数:全局已预加载 toy 对象——await toy.set({ intensity, stroke }) 改变强度/行程、'
595
624
  + 'await toy.sleep(毫秒) 控制节奏、toy.stop() 停止;不接触任何通信细节。'
596
- + '每个玩具脚本必须在自行判断的合适位置调用 await toy.wake({ mood, topic, reason }),请导演感知脚本中的变化并决定是否开口。'
625
+ + '每个玩具脚本必须在自行判断的合适位置调用 await toy.wake({ mood, topic, reason }),请导演感知脚本中的变化并决定是否开口。'
597
626
  + '脚本与运行日志完全透明可监管:管理台「玩具操控脚本」可查看运行状态与日志(toys/.logs/)。'
598
- + '脚本自然结束即终止,结束时设备保持最后的参数继续运行并提醒你;中途停可用 stop=runId '
599
- + '或 toy_control stop。每次只有一段脚本在跑,新的调用会接管。\n'
600
- + '要先激活设备(用户发分享链接);激活后参考脚本会位于 toys/玩具脚本示例.mjs。',
627
+ + '脚本启动时会清除尚未到期的 toy_control 计时提醒,避免旧控制事件与脚本撞车。'
628
+ + '脚本自然结束即终止,结束时设备保持最后的参数继续运行并优先提醒你;中途停可用 stop=runId '
629
+ + '或 toy_control stop。脚本运行期间不得直接改用 toy_control 接管;若要改用,必须先显式停止该脚本并确认停止。'
630
+ + '每次只有一段脚本在跑,新的脚本调用会接管旧脚本。\n'
631
+ + '要先激活设备(用户发分享链接);激活后参考脚本会位于 toys/玩具脚本示例.mjs。',
601
632
  parameters: {
602
633
  type: 'object',
603
634
  additionalProperties: false,
@@ -638,27 +669,27 @@ export function buildDirectorToolDefs(resolveCtx) {
638
669
  if (!c.roleId) return { ok: false, error: '无角色上下文' };
639
670
  // stop 模式
640
671
  if (typeof args?.stop === 'string' && args.stop.trim()) {
641
- const res = await c.devices.stopScript(args.stop.trim());
672
+ const res = await c.devices.stopScript(args.stop.trim(), c.roleId);
642
673
  return res.ok ? { ok: true, stopped: res.stopped } : { ok: false, error: res.error || '终止失败' };
643
674
  }
644
675
  const ws = typeof c.workspaceOf === 'function' ? await c.workspaceOf() : null;
645
676
  if (!ws) return { ok: false, error: '无角色工作区上下文' };
646
677
  const toysDir = join(ws, 'toys');
647
678
  let names = [];
648
- try { names = (await readdir(toysDir)).filter((n) => /\.(mjs|js|ts)$/.test(n) && n !== TOY_REFERENCE_NAME); } catch { /* 目录不存在 */ }
679
+ try { names = (await readdir(toysDir)).filter((n) => /\.(mjs|js|ts)$/.test(n) && n !== TOY_REFERENCE_NAME); } catch { /* 目录不存在 */ }
649
680
  let given = typeof args?.script === 'string' ? String(args.script).trim() : '';
650
681
  let scriptPath;
651
- if (given) {
652
- if (given === TOY_REFERENCE_NAME) return { ok: false, error: '玩具脚本示例仅供先阅读参考,请新建自己的脚本后再运行。' };
653
- const p = join(toysDir, given);
654
- if (!existsSync(p)) return { ok: false, error: `toys/${given} 不存在(现有: ${names.join(', ') || '无'})` };
655
- scriptPath = p;
682
+ if (given) {
683
+ if (given === TOY_REFERENCE_NAME) return { ok: false, error: '玩具脚本示例仅供先阅读参考,请新建自己的脚本后再运行。' };
684
+ const p = join(toysDir, given);
685
+ if (!existsSync(p)) return { ok: false, error: `toys/${given} 不存在(现有: ${names.join(', ') || '无'})` };
686
+ scriptPath = p;
656
687
  } else {
657
688
  const main = names.find((n) => /^(main|index)\./.test(n)) ?? names[0];
658
689
  if (!main) return { ok: false, error: 'toys/ 下还没有脚本——先用文件工具新建一个 .mjs 再 toy_run_script(参考 templates/sample-toy.mjs)。' };
659
690
  scriptPath = join(toysDir, main);
660
- }
661
- const role = c.persona && c.roleId ? await c.persona.loadRole(c.roleId).catch(() => null) : null;
691
+ }
692
+ const role = c.persona && c.roleId ? await c.persona.loadRole(c.roleId).catch(() => null) : null;
662
693
  const res = await c.devices.runScript({
663
694
  roleId: c.roleId,
664
695
  scriptPath,
@@ -666,6 +697,7 @@ export function buildDirectorToolDefs(resolveCtx) {
666
697
  httpApiToken: c.httpApiToken,
667
698
  httpApiPath: c.httpApiPath,
668
699
  openid: role?.binding?.openid,
700
+ roleScopedHook: c.target()?.kind === 'direct',
669
701
  reason: args?.reason,
670
702
  });
671
703
  return res.ok
@@ -855,7 +887,7 @@ export function buildMemeToolDefs(resolveCtx) {
855
887
  // meme_send:发送一张表情包
856
888
  {
857
889
  name: 'meme_send',
858
- description: '向当前 QQ 聊天发送一张表情包图片。用 memeId(优先,从 meme_find 拿到)或本地文件路径。'
890
+ description: '向当前聊天发送一张表情包图片。用 memeId(优先,从 meme_find 拿到)或本地文件路径。'
859
891
  + '可带 text 作为配文。发送成功会记录使用时间。',
860
892
  parameters: {
861
893
  type: 'object', additionalProperties: false,
@@ -1084,6 +1116,7 @@ export function registerDirectorTools(agentCtx, sessionId, deps) {
1084
1116
  persona: deps.persona, log: deps.log, workspaceOf: deps.workspaceOf,
1085
1117
  subagents: deps.subagents, llm: deps.llm,
1086
1118
  devices: deps.devices,
1119
+ voice: deps.voice, beginDelivery: deps.beginDelivery,
1087
1120
  });
1088
1121
  for (const def of buildDirectorToolDefs(resolveCtx))
1089
1122
  tools.register(def);
@@ -1101,7 +1134,8 @@ export function registerDirectorTools(agentCtx, sessionId, deps) {
1101
1134
  * (可能为 async:宿主服务可在未命中时按 sessionId 惰性构造依赖)
1102
1135
  * @returns 是否完成注册
1103
1136
  */
1104
- export function registerStandingTools(ctx, depsFor) {
1137
+ export const CHAT_TOOL_NAMES = ['director_send', 'recollect', 'qq_send_media', 'meme_find', 'meme_send'];
1138
+ export function registerStandingTools(ctx, depsFor, names, disposers) {
1105
1139
  const tools = ctx.tools;
1106
1140
  if (tools === undefined)
1107
1141
  return false;
@@ -1112,21 +1146,35 @@ export function registerStandingTools(ctx, depsFor) {
1112
1146
  const deps = await depsFor(sessionId);
1113
1147
  if (deps === undefined)
1114
1148
  throw new Error(`pygmalion: 会话 ${sessionId} 的 pygmalion 上下文未注册(setup 未运行?该 agent 并非由 pygmalion 启动?)`);
1149
+ const role = deps.roleId && await deps.persona?.loadRole?.(deps.roleId);
1150
+ const target = deps.target?.() ?? targetOfSession(sessionId);
1151
+ const ownsChat = !exec.agent.session?.header?.parentSession && matchesRoleTarget(role, target, deps.identityScope);
1152
+ if (deps.roleId && !exec.agent.session?.header?.parentSession && !ownsChat)
1153
+ throw new Error('当前会话不是该角色绑定的私人聊天,不能读取记忆或执行角色能力');
1154
+ if (names?.some(n => n.startsWith('toy_')) && (!ownsChat || !role.persona?.devices?.length))
1155
+ throw new Error('当前角色无设备操控授权');
1115
1156
  return {
1116
1157
  sessionId,
1117
1158
  api: deps.api, routes: deps.routes,
1118
1159
  target: () => deps.target?.() ?? targetOfSession(sessionId),
1119
1160
  roleId: deps.roleId, httpApiToken: deps.httpApiToken, httpApiPath: deps.httpApiPath,
1120
1161
  persona: deps.persona, log: deps.log, workspaceOf: deps.workspaceOf,
1121
- subagents: deps.subagents, llm: deps.llm,
1162
+ subagents: deps.subagents, llm: deps.llm, sessionPersistence: deps.sessionPersistence,
1122
1163
  devices: deps.devices,
1164
+ identityScope: deps.identityScope,
1165
+ voice: deps.voice, beginDelivery: deps.beginDelivery,
1123
1166
  };
1124
1167
  };
1125
- for (const def of buildQQToolDefs(resolveCtx))
1126
- tools.register(def);
1127
- for (const def of buildDirectorToolDefs(resolveCtx))
1128
- tools.register(def);
1129
- for (const def of buildMemeToolDefs(resolveCtx))
1130
- tools.register(def);
1168
+ const definitions = [...buildQQToolDefs(resolveCtx), ...buildDirectorToolDefs(resolveCtx), ...buildMemeToolDefs(resolveCtx)];
1169
+ const privileged = new Set(['director_send', 'qq_send_media', 'qq_api', 'meme_send', 'toy_control', 'toy_run_script', 'life_run']);
1170
+ for (const def of definitions.filter(def => !names || names.includes(def.name))) {
1171
+ const execute = def.execute;
1172
+ const release = tools.register({ ...def, async execute(args, exec) {
1173
+ if (privileged.has(def.name) && exec?.agent?.session?.header?.parentSession)
1174
+ throw new Error('工作子会话不可发送 QQ 消息或操控设备/生活脚本');
1175
+ return execute(args, exec);
1176
+ } });
1177
+ disposers?.push(release);
1178
+ }
1131
1179
  return true;
1132
1180
  }