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/tools.js CHANGED
@@ -1,20 +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 { isVoiceSynthesisTimeout, synthesizeMiMoVoice } from './voice-mimo.js';
12
- import { normalizeDirectorMessages, reviewDirectorSend, validateDirectorMessages } from './message-review.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';
13
15
 
14
16
  const IMAGE_EXTS = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.svg', '.ico']);
15
- const VOICE_EXTS = new Set(['.wav', '.mp3', '.silk', '.amr', '.ogg', '.flac', '.aac', '.m4a']);
16
- /** sessionId → 最近一次因硬校验/审查退回而保留的 reawake.id;重试时精确替换,避免队列堆积。 */
17
- const rejectedReawakeBySession = new Map();
17
+ const VOICE_EXTS = new Set(['.wav', '.mp3', '.silk', '.amr', '.ogg', '.flac', '.aac', '.m4a']);
18
+ /** sessionId → 最近一次因参数校验退回而保留的 reawake.id;重试时精确替换,避免队列堆积。 */
19
+ const rejectedReawakeBySession = new Map();
18
20
 
19
21
  /** dsh 工具输出要求无损 JSON(拒绝 undefined/NaN/非有限数);返回前剥掉 undefined 字段。 */
20
22
  function noUndefined(obj) {
@@ -74,9 +76,9 @@ export function buildQQToolDefs(resolveCtx) {
74
76
  return [
75
77
  {
76
78
  name: 'qq_send_media',
77
- description: 'Send an image, voice, video, or file message to the current QQ chat. '
79
+ description: 'Send media supported by the current chat connection. '
78
80
  + 'Accepts an https URL, a data: URL, or an absolute local file path '
79
- + '(files larger than 10MB upload through the chunked pipeline automatically). '
81
+ + '(encoding and upload limits are defined by the connection). '
80
82
  + 'Use this instead of pasting image URLs as text when the user asks for a media message.',
81
83
  parameters: {
82
84
  type: 'object',
@@ -170,51 +172,50 @@ export function buildDirectorToolDefs(resolveCtx) {
170
172
  // director_send:向当前 QQ 用户发送聊天消息(导演模式的唯一发送通道)。
171
173
  {
172
174
  name: 'director_send',
173
- description: '让角色向当前 QQ 用户发送聊天消息(本模式的唯一发送通道)。QQ 用户在与角色交流,不是在与导演交流。'
174
- + 'messages 是按顺序发送的 QQ 消息气泡,每个普通文字气泡写一个自然说出的语块。闲聊回应通常是一至两条,但没有固定条数上限;'
175
- + '主动展开确有多个连续想法的话题时可以自然地发更多条。文字通常不用逗号把多个本可独立说出的分句压成长句,停顿、转折、补充或另起一个意思时直接开始下一条;'
176
- + '不要为增加数量机械拆句,也不要为减少数量塞成长句,想说完就停。不写大段文章、markdown、动作描写、心理旁白或括号情绪标签。'
177
- + '【reawake 是默认动作】发送消息时,几乎每一次都应该同时带上 reawake 参数。'
178
- + 'reawake 填一个正数,表示多少分钟后若用户没有回复,系统会在到点唤醒你重新审视情境;'
175
+ description: '向当前聊天对象提交角色真正要说的消息(本模式的唯一发送通道)。'
176
+ + 'messages 每项是一条文字或语音消息。表达风格、标点、语气词及分条习惯,按当前人物设定与场景决定。'
177
+ + '普通文字不包含幕后分析、心理旁白、舞台说明或括号情绪标签。'
178
+ + '【reawake 是默认动作】发送消息时,几乎每一次都应该同时带上 reawake 参数。'
179
+ + 'reawake 填一个正数,表示多少分钟后若用户没有回复,系统会在到点唤醒你重新审视情境;'
179
180
  + '填 "none" 或省略则表示不安排。这是维持主动联系、不让关系冷掉的机制,不安排就意味着'
180
- + '这轮聊完之后你将一直静默等待用户。时长应符合真实生活,考虑用户可能离开手机、双方正在做的事、明确约定、'
181
- + '届时情境是否可能变化以及连续没有回复后自然延长的等待,不套用固定区间。reason 只记录届时重新观察的情况,'
182
- + '不预写下一条消息,也不预设醒来后一定开口。'
183
- + 'messages 为空数组时可只安排 reawake 而本次不发。'
184
- + '只允许发送拟真的、贴合角色性格的聊天文本;绝不发送思考、计划、动作描述、工具说明或任何非消息内容。'
185
- + '文本与语音须像真人使用 QQ 那样随情景自然选择,既不能每条都发语音,也不能长期完全不用语音。'
186
- + '语音项的 text 是原样朗读的台词;scene 写清当前事件、对象和人物动机;direction 只给一句整段成立的表演意图。'
187
- + '语音合成按台词长度设置等待时限;若超时,系统会自动把同一台词作为文字发送,并在工具结果中明确说明。'
188
- + '角色音色身份已经由管理页配置,不要在语音项重复。禁止用“前面/中段/后面”等模糊时序词、逐句声学控制、旁白或台词外心理活动。'
189
- + '仅语音 text 可在必要处加入少量简短的中文圆括号语义标签,如“(轻笑)”“(压低声音)”“(停顿)”,供语音模型控制表演;'
190
- + '不把场景、心理活动或长指令塞进标签,也不用标签编排逐句变化。'
191
- + '如果你决定此刻不打扰对方,就不要调用本工具。',
181
+ + '这轮聊完之后你将一直静默等待用户。时长应符合真实生活,考虑用户可能离开手机、双方正在做的事、明确约定、'
182
+ + '届时情境是否可能变化以及连续没有回复后自然延长的等待,不套用固定区间。reason 只记录届时重新观察的情况,'
183
+ + '不预写下一条消息,也不预设醒来后一定开口。'
184
+ + 'messages 为空数组时可只安排 reawake 而本次不发。'
185
+ + '只允许发送拟真的、贴合角色性格的聊天文本;绝不发送思考、计划、动作描述、工具说明或任何非消息内容。'
186
+ + '文本与语音须像真人聊天 那样随情景自然选择,既不能每条都发语音,也不能长期完全不用语音。'
187
+ + '语音项的 text 是原样朗读的台词;scene 写清当前事件、对象和人物动机;direction 只给一句整段成立的表演意图。'
188
+ + '语音合成按台词长度设置等待时限;若超时,系统会自动把同一台词作为文字发送,并在工具结果中明确说明。'
189
+ + '角色音色身份已经由管理页配置,不要在语音项重复。禁止用“前面/中段/后面”等模糊时序词、逐句声学控制、旁白或台词外心理活动。'
190
+ + '仅当当前语音能力明确支持括号表演标签时,语音 text 才可少量使用简短标签;否则台词只包含真正朗读的文字。'
191
+ + '不把场景、心理活动或长指令塞进标签,也不用标签编排逐句变化。'
192
+ + '如果你决定此刻不打扰对方,就不要调用本工具。',
192
193
  parameters: {
193
194
  type: 'object',
194
195
  additionalProperties: false,
195
196
  properties: {
196
- messages: {
197
- type: 'array',
198
- items: { oneOf: [
199
- { type: 'string' },
200
- { type: 'object', additionalProperties: false, required: ['type', 'text'], properties: {
201
- type: { type: 'string', enum: ['text', 'voice'] },
202
- text: { type: 'string', description: '普通文字的发送内容,或 voice 的朗读台词。普通文字不使用括号情绪/动作标签;仅语音台词可用少量简短圆括号语义标签控制表演,如“(轻笑)”。' },
203
- scene: { type: 'string', description: '仅 voice:本条语音的完整情景、对话对象与情绪动机;不要重复管理页角色设定。' },
204
- direction: { type: 'string', description: '仅 voice:一句整体表演方向;不编排逐句变化时机,不写模糊时序词或旁白。语音表演所需的简短语义标签放在 voice 的 text 中。' },
205
- } },
206
- ] },
207
- 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 由角色所选语音服务合成并发送。空数组或省略 = 不发送。',
208
209
  },
209
210
  reawake: {
210
211
  oneOf: [{ type: 'number' }, { type: 'string' }],
211
- description: '建议默认携带。具体分钟数须按真实情境决定:考虑用户可能离开手机、双方正在做的事、明确约定、'
212
- + '届时情境是否可能变化,以及连续没有回复后自然延长的等待;不要套用固定区间。'
212
+ description: '建议默认携带。具体分钟数须按真实情境决定:考虑用户可能离开手机、双方正在做的事、明确约定、'
213
+ + '届时情境是否可能变化,以及连续没有回复后自然延长的等待;不要套用固定区间。'
213
214
  + '填正数会登记等待队列;明确决定这轮不再续聊时才写 "none" 或省略。',
214
215
  },
215
216
  reason: {
216
217
  type: 'string',
217
- description: '可选:reawake 到期时需要重新观察的情境线索。不要预写下一条消息,也不要预设届时一定开口。',
218
+ description: '可选:reawake 到期时需要重新观察的情境线索。不要预写下一条消息,也不要预设届时一定开口。',
218
219
  },
219
220
  },
220
221
  },
@@ -222,152 +223,147 @@ export function buildDirectorToolDefs(resolveCtx) {
222
223
  schema: {
223
224
  type: 'object',
224
225
  additionalProperties: false,
225
- properties: {
226
- ok: { type: 'boolean' }, sent: { type: 'number' }, textSent: { type: 'number' }, voiceSent: { type: 'number' },
227
- voiceTimeouts: { type: 'array', items: { type: 'number' } },
228
- failedAt: { type: 'number' }, reawake: { type: 'number' }, error: { type: 'string' },
229
- },
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
+ },
230
232
  required: ['ok', 'sent'],
231
233
  },
232
- render: (_args, value) => {
233
- const timedOut = Array.isArray(value.voiceTimeouts) ? value.voiceTimeouts : [];
234
- const timeoutText = timedOut.length > 0
235
- ? `(第 ${timedOut.join('、')} 条语音合成超时,已自动改发文字)`
236
- : '';
237
- return [{ type: 'text', text: value.ok
238
- ? `已发送 ${value.sent} 条消息${timeoutText}${value.reawake ? `,已安排 ${value.reawake} 延时唤醒` : ''}`
239
- : `发送失败: ${value.error ?? '?'}${value.sent > 0 ? `(失败前已发送 ${value.sent} 条消息)` : ''}`
240
- + timeoutText + `${value.reawake ? '(有效的延时唤醒已保留)' : ''}` }];
241
- },
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
+ },
242
245
  },
243
- timeoutMs: 360_000,
244
- async execute(args, exec) {
245
- const c = await resolveCtx(args, exec);
246
- const raw = Array.isArray(args?.messages) ? args.messages : [];
247
- const messages = normalizeDirectorMessages(raw);
248
- // 有效的 reawake 先登记。即使候选消息随后被硬校验或独立审查退回,关系仍有
249
- // 下一次继续的可能;dsh 在当前轮重试时会用新安排覆盖它。
250
- const ra = args?.reawake;
251
- let reawakeAt;
252
- let reawakeMinutes;
253
- let scheduledReawakeId;
254
- if (ra !== undefined && ra !== null && ra !== 'none' && ra !== 'NONE') {
255
- const minutes = typeof ra === 'number' ? ra : Number(String(ra).trim());
256
- if (!Number.isFinite(minutes) || minutes <= 0)
257
- return { ok: false, sent: 0, error: 'reawake 必须是正数分钟、"none" 或省略' };
258
- const replaceId = rejectedReawakeBySession.get(c.sessionId);
259
- const rw = c.roleId && c.persona?.scheduleRewake
260
- ? await c.persona.scheduleRewake(c.roleId, minutes, typeof args?.reason === 'string' ? args.reason : '',
261
- replaceId === undefined ? {} : { replaceId })
262
- : { ok: false, atMs: 0, error: '无角色上下文' };
263
- if (!rw.ok) return { ok: false, sent: 0, error: `reawake 安排失败: ${rw.error ?? '?'}` };
264
- reawakeAt = rw.atMs;
265
- reawakeMinutes = minutes;
266
- rejectedReawakeBySession.delete(c.sessionId);
267
- // 只有随后确实退回时才重新放入 map;正常发送保留原有“多个独立等待可并存”语义。
268
- scheduledReawakeId = rw.id;
269
- }
270
- const withReawake = (value) => reawakeAt ? { ...value, reawake: reawakeAt } : value;
271
- const hardIssues = validateDirectorMessages(raw, messages);
272
- if (hardIssues.length > 0) {
273
- if (scheduledReawakeId !== undefined) rejectedReawakeBySession.set(c.sessionId, scheduledReawakeId);
274
- return withReawake({ ok: false, sent: 0, error: `消息未发送:${hardIssues.join(';')}` });
275
- }
276
-
277
- // 审查器默认复用当前会话实际的 provider/model。调用故障时 fail-open;审查明确
278
- // 退回时不发送,但保留上面已经登记的 reawake,避免辅助能力破坏主动连续性。
279
- const role = c.roleId && c.persona?.loadRole ? await c.persona.loadRole(c.roleId) : undefined;
280
- if (role && role.proactive?.messageReview?.enabled !== false && (messages.length > 0 || reawakeMinutes !== undefined)) {
281
- try {
282
- const review = await reviewDirectorSend({
283
- llm: c.llm, agent: exec?.agent, role, messages,
284
- reawake: reawakeMinutes, reason: args?.reason,
285
- });
286
- const reviewIssues = [];
287
- if (messages.length > 0 && !review.messages.pass)
288
- reviewIssues.push(...(review.messages.reasons.length
289
- ? review.messages.reasons : ['候选消息不符合自然 QQ 交流习惯']));
290
- if (reawakeMinutes !== undefined && !review.reawake.reasonable)
291
- reviewIssues.push(review.reawake.reason || 'reawake 时长不符合当前真实情境');
292
- if (reviewIssues.length > 0) {
293
- if (scheduledReawakeId !== undefined) rejectedReawakeBySession.set(c.sessionId, scheduledReawakeId);
294
- c.log?.info?.('pygmalion: director_send 审查退回 role=%s model=%s/%s issues=%s',
295
- c.roleId, review.route.provider, review.route.model, reviewIssues.join(';'));
296
- return withReawake({ ok: false, sent: 0,
297
- error: `发送前审查未通过,请重新判断后重试或保持沉默:${reviewIssues.join(';')}` });
298
- }
299
- }
300
- catch (error) {
301
- c.log?.warn?.('pygmalion: director_send 审查不可用,按 fail-open 放行 role=%s: %o', c.roleId, error);
302
- }
303
- }
304
- const sent = [];
305
- const deliveredTypes = [];
306
- const voiceTimeouts = [];
307
- if (messages.length > 0) {
308
- const record = c.routes?.get(c.sessionId);
309
- const passive = record
310
- ? c.routes.consumePassive(c.sessionId, record.target.kind === 'group' ? 5 * 60 * 1000 : 30 * 60 * 1000, 4)
311
- : undefined;
312
- for (let messageIndex = 0; messageIndex < messages.length; messageIndex++) {
313
- const msg = messages[messageIndex];
314
- try {
315
- exec?.signal?.throwIfAborted?.();
316
- if (msg.type === 'voice') {
317
- if (!c.roleId) throw new Error('当前会话没有角色语音配置');
318
- const synthesizeVoice = typeof c.synthesizeVoice === 'function' ? c.synthesizeVoice : synthesizeMiMoVoice;
319
- try {
320
- const audio = await synthesizeVoice({ roleId: c.roleId, text: msg.text, scene: msg.scene,
321
- direction: msg.direction, signal: exec?.signal });
322
- try { await c.api.sendMedia(c.target(), 'voice', audio.file, { passiveMsgId: passive }); }
323
- finally { await audio.cleanup(); }
324
- deliveredTypes.push('voice');
325
- }
326
- catch (error) {
327
- if (!isVoiceSynthesisTimeout(error)) throw error;
328
- exec?.signal?.throwIfAborted?.();
329
- await c.api.sendText(c.target(), msg.text, passive);
330
- voiceTimeouts.push(messageIndex + 1);
331
- deliveredTypes.push('text');
332
- }
333
- } else {
334
- await c.api.sendText(c.target(), msg.text, passive);
335
- deliveredTypes.push('text');
336
- }
337
- sent.push(msg);
338
- }
339
- catch (error) {
340
- return withReawake({
341
- ok: false, sent: sent.length, failedAt: sent.length,
342
- voiceTimeouts,
343
- error: error instanceof Error ? error.message : String(error),
344
- });
246
+ timeoutMs: 360_000,
247
+ async execute(args, exec) {
248
+ const c = await resolveCtx(args, exec);
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: [] };
291
+ if (messages.length > 0) {
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' });
334
+ }
335
+ catch (error) {
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,
340
+ error: error instanceof Error ? error.message : String(error),
341
+ });
345
342
  }
346
343
  }
347
344
  // 日期层记忆:角色消息发出后延迟从活跃会话 session log 提取写原始记录
348
345
  // (等 dsh 把 director_send 工具调用落盘;仅 c2c 拥有者会话)。
349
- if (sent.length > 0 && c.target()?.kind === 'c2c') {
346
+ if (sent.length > 0 && matchesRoleTarget(await c.persona?.loadRole?.(c.roleId), c.target(), c.identityScope)) {
350
347
  const workspace = c.workspaceOf
351
348
  ? await c.workspaceOf()
352
349
  : (c.persona && c.roleId ? c.persona.roleWorkspace(c.roleId) : undefined);
353
350
  if (workspace && c.sessionId) {
354
- const file = sessionFileFor({ sessionId: c.sessionId, workspace });
355
351
  // 会话文件不存在则无内容可提取(测试/调试 stub 路径跳过,避免挂空定时器)。
356
- if (existsSync(file)) {
352
+ if (c.sessionPersistence) {
357
353
  const charLabel = c.roleId && c.persona ? await charLabelOf(c.persona, c.roleId) : '角色';
358
354
  setTimeout(() => {
359
- void refreshRawRecordFromSession({ workspace, sessionFile: file, charLabel, log: c.log })
355
+ void refreshRawRecordFromSession({ workspace, sessionId: c.sessionId, persistence: c.sessionPersistence, charLabel, log: c.log })
360
356
  .catch((error) => c.log?.warn?.('pygmalion: 刷新原始记录失败: %o', error));
361
357
  }, 3000);
362
358
  }
363
359
  }
364
360
  }
365
- }
366
- return withReawake({ ok: true, sent: sent.length,
367
- textSent: deliveredTypes.filter((type) => type === 'text').length,
368
- voiceSent: deliveredTypes.filter((type) => type === 'voice').length,
369
- voiceTimeouts });
370
- },
361
+ }
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 });
366
+ },
371
367
  },
372
368
  // recollect:按需回忆(只在需要回忆/找话题时调用)
373
369
  {
@@ -393,7 +389,7 @@ export function buildDirectorToolDefs(resolveCtx) {
393
389
  required: ['found', 'text'],
394
390
  },
395
391
  render: (_args, value) => [
396
- { type: 'text', text: value.found ? `[回忆]\n${String(value.text).slice(0, 4000)}` : '(记忆中没有相关内容)' },
392
+ { type: 'text', text: value.found ? `[回忆]\n${String(value.text)}` : '(记忆中没有相关内容)' },
397
393
  ],
398
394
  },
399
395
  timeoutMs: 20_000,
@@ -401,49 +397,7 @@ export function buildDirectorToolDefs(resolveCtx) {
401
397
  const c = await resolveCtx(args, exec);
402
398
  const ws = typeof c.workspaceOf === 'function' ? await c.workspaceOf() : null;
403
399
  if (!ws) return { found: false, text: '' };
404
- const mem = join(ws, 'memory');
405
- const out = [];
406
- // 特殊记忆:对 TA 的印象/重要事件(dsh 直接编辑);空白模板不返回。
407
- try {
408
- const aboutUser = (await readFile(join(mem, '关于TA.md'), 'utf8')).trim();
409
- if (aboutUser && aboutUser !== '(空白,等待你记录对 TA 的了解)')
410
- out.push(`== 关于TA(特殊记忆)==\n${aboutUser.slice(0, 2000)}`);
411
- } catch { /* 尚无特殊记忆 */ }
412
- // 话题层:topics/<话题>[YYYY-MM-DD HH:MM:SS-YYYY-MM-DD HH:MM:SS]/索引.md
413
- try {
414
- const subs = (await readdir(join(mem, 'topics'))).filter((n) => !n.startsWith('.')).sort().reverse();
415
- for (const name of subs.slice(0, 20)) {
416
- try {
417
- const ti = await readFile(join(mem, 'topics', name, '索引.md'), 'utf8');
418
- out.push(`== 话题 ${name} ==\n${ti.slice(0, 1200)}`);
419
- } catch { /* 该话题无索引 */ }
420
- }
421
- } catch { /* 无话题层 */ }
422
- // 日期层:索引(默认最近 N 天;指定日期则附当日原文片段)
423
- let dates = [];
424
- try { dates = (await readdir(mem)).filter((n) => /^\d{4}-\d{2}-\d{2}$/.test(n)).sort().reverse(); } catch { /* no memory yet */ }
425
- if (dates.length) {
426
- const limit = Math.min(Math.max(Number(args?.limit) || 3, 1), 10);
427
- const pick = args?.date ? [String(args.date)] : dates.slice(0, limit);
428
- for (const d of pick) {
429
- const idx = join(mem, d, '索引.md');
430
- const raw = join(mem, d, '原始记录.md');
431
- try {
432
- let t = `== ${d} 索引 ==\n` + await readFile(idx, 'utf8');
433
- if (args?.date && args.date === d) {
434
- try { t += `\n== ${d} 原文(片段) ==\n` + (await readFile(raw, 'utf8')).slice(0, 2000); } catch { /* 无原文 */ }
435
- }
436
- out.push(t);
437
- } catch { /* 该日无索引 */ }
438
- }
439
- }
440
- let text = out.join('\n\n');
441
- if (args?.topic) {
442
- const q = String(args.topic).toLowerCase();
443
- const filtered = text.split('\n').filter((l) => l.toLowerCase().includes(q));
444
- text = filtered.length ? filtered.join('\n') : text;
445
- }
446
- return text.trim() ? { found: true, text: text.trim().slice(0, 6000) } : { found: false, text: '' };
400
+ return recallMemory(ws, args);
447
401
  },
448
402
  },
449
403
  // life_run:在插件监管下启动/终止角色生活脚本(dsh 全权决定运行,插件只监管展示)
@@ -452,18 +406,18 @@ export function buildDirectorToolDefs(resolveCtx) {
452
406
  description: '启动你在 life/ 下写的角色生活脚本(.mjs/.js/.py/.ts,可指定文件名)。'
453
407
  + '脚本是“角色生活的程序化模拟器”:由你创作角色在聊天之外的经历并程序化(一天的节奏、'
454
408
  + '习惯、社交、心情变化、突发小事件),把经历写成可读记录(如 life/<名>.log 或工作区文件),'
455
- + '这样角色有自己的生活,聊天时有真实经历可谈——而不是简单的“用户很久没回就去找用户”。'
409
+ + '这样角色有自己的生活,聊天时有真实经历可谈——而不是简单的“用户很久没回就去找用户”。'
456
410
  + '脚本何时运行、怎么写、何时结束完全由你决定:可以长驻循环(while/setInterval),结束条件'
457
411
  + '写在脚本里;插件不限制运行时长/次数,只登记运行状态、把输出写进 life/.logs/,并在管理页'
458
412
  + '展示脚本内容与运行日志(受监管)。启动立即返回 runId/pid,脚本在后台继续跑;'
459
413
  + '要终止用 stop=<runId>。'
460
414
  + '脚本以“有事件就唤醒”为设计原则:脚本里设计的每个生活事件(心情变化、到点作息、'
461
- + '突发小事件、想用户的时刻)在发生时都调用 wake({ mood, topic, reason, force }) —— node '
415
+ + '突发小事件、想用户的时刻)在发生时都调用 wake({ mood, topic, reason, force }) —— node '
462
416
  + '脚本启动时已自动预加载全局 wake(),直接调用即可(无需 import / fetch / 网络):内部经'
463
417
  + 'HTTP 调插件 /wakeup 端点,插件节流(默认同角色 10 分钟内至多一次)+ 撞车检测后'
464
418
  + '唤醒 dsh 注入 [脚本事件] 情境;是否开口、如何开口由你(导演)被唤醒后自行判断'
465
- + '(可以选择沉默)。wake() 的意义是让事件成为导演已经知晓的角色经历;事件被知晓后目的已经达成,'
466
- + '是否把它转化成 QQ 消息是另一项独立判断。'
419
+ + '(可以选择沉默)。wake() 的意义是让事件成为导演已经知晓的角色经历;事件被知晓后目的已经达成,'
420
+ + '是否把它转化成 QQ 消息是另一项独立判断。'
467
421
  + '重要:唤醒消息里只包含 wake() 参数中的文本(mood/topic/reason 会注入 [脚本事件]'
468
422
  + '情境);脚本其它任何输出(console.log、写日志/日记文件等)都不会进入唤醒消息——'
469
423
  + '想让导演在唤醒时看到的情境,必须写进 wake() 参数,否则对唤醒毫无意义。'
@@ -540,6 +494,7 @@ export function buildDirectorToolDefs(resolveCtx) {
540
494
  token: c.httpApiToken,
541
495
  httpApiPath: c.httpApiPath,
542
496
  openid: role?.binding?.openid,
497
+ roleScopedHook: c.target()?.kind === 'direct',
543
498
  });
544
499
  return res.ok
545
500
  ? { ok: true, runId: res.runId, pid: res.pid, startedAt: res.startedAt, script: res.script }
@@ -549,7 +504,7 @@ export function buildDirectorToolDefs(resolveCtx) {
549
504
  // toy_status:查询角色可用设备状态
550
505
  {
551
506
  name: 'toy_status',
552
- description: '查询当前角色已授权可用设备的状态:是否已激活(用户是否发过分享链接)、当前运行状态'
507
+ description: '查询当前角色已授权可用设备的状态:是否已激活(用户是否发过分享链接)、当前运行状态'
553
508
  + '(controller/last 参数/是否有脚本在跑)。需要操作设备前可先调用确认。',
554
509
  parameters: {
555
510
  type: 'object',
@@ -573,7 +528,7 @@ export function buildDirectorToolDefs(resolveCtx) {
573
528
  if (!v?.ok) text = `toy_status 失败: ${v?.error ?? '?'}`;
574
529
  else if (!v.devices?.length) text = '该角色未配置可用设备。';
575
530
  else {
576
- 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 ? '已激活' : '未激活——需用户发分享链接'}`
577
532
  + (d.activated ? ` | 运行:${d.controller}${d.last ? ` 参数=${d.last.intensity !== 0 || d.last.stroke ? JSON.stringify(d.last) : ''}` : ''}${d.runId ? ` | 脚本=${d.runId}` : ''}` : ''));
578
533
  text = ['可用设备:'].concat(lines).join('\n');
579
534
  }
@@ -585,19 +540,19 @@ export function buildDirectorToolDefs(resolveCtx) {
585
540
  const c = await resolveCtx(_args, exec);
586
541
  if (!c.devices) return { ok: false, error: '设备服务不可用' };
587
542
  if (!c.roleId) return { ok: false, error: '无角色上下文' };
588
- return await c.devices.status(c.roleId);
543
+ return await (c.devices.monsterpartyStatus?.(c.roleId) ?? c.devices.status(c.roleId));
589
544
  },
590
545
  },
591
546
  // toy_control:定时/即时操控设备(工具调用模式)
592
547
  {
593
548
  name: 'toy_control',
594
- description: '操控当前角色可用的玩具设备(行程+强度)。需要用户已发过一条新鲜分享链接(激活),否则会提示先请用户发。\n'
549
+ description: '操控当前角色可用的玩具设备(行程+强度)。需要用户已发过一条新鲜分享链接(激活),否则会提示先请用户发。\n'
595
550
  + '参数:intensity 强度 0-100;stroke 行程范围(用两个边界,取值 0/33/66/100,如 "0,100"=L1~L3 全行程往复、'
596
551
  + '"0,66"=L1~L2 区间、"0,0"=停住;也可写区间名 "L1,L2");seconds 本次操作的时长(秒)。\n'
597
552
  + '计时语义:到点后设备保持当前参数继续运行,系统会提醒你计时结束,可再次调用本工具调整或 stop。'
598
- + '设备无自动停止——由你决定何时停(用户要求停时必须停);停用 stop:true。\n'
599
- + '注意:玩具脚本运行期间,除 stop:true 外本工具不会接管控制。若要改用 toy_control 操控,必须先显式停止正在运行的脚本:'
600
- + '调用 toy_run_script 的 stop=<runId>(或单独调用 toy_control stop:true 停止脚本和设备),确认停止后再发起新的 toy_control 控制。',
553
+ + '设备无自动停止——由你决定何时停(用户要求停时必须停);停用 stop:true。\n'
554
+ + '注意:玩具脚本运行期间,除 stop:true 外本工具不会接管控制。若要改用 toy_control 操控,必须先显式停止正在运行的脚本:'
555
+ + '调用 toy_run_script 的 stop=<runId>(或单独调用 toy_control stop:true 停止脚本和设备),确认停止后再发起新的 toy_control 控制。',
601
556
  parameters: {
602
557
  type: 'object',
603
558
  additionalProperties: false,
@@ -626,7 +581,7 @@ export function buildDirectorToolDefs(resolveCtx) {
626
581
  let text;
627
582
  if (!v?.ok) {
628
583
  const err = v?.error ?? '?';
629
- text = `toy_control 失败: ${err}${err.includes('激活') || err.includes('分享链接') ? '(让用户发一条新鲜分享链接即可)' : ''}`;
584
+ text = `toy_control 失败: ${err}${err.includes('激活') || err.includes('分享链接') ? '(让用户发一条新鲜分享链接即可)' : ''}`;
630
585
  } else {
631
586
  const s = v.state;
632
587
  const last = s?.last;
@@ -661,19 +616,19 @@ export function buildDirectorToolDefs(resolveCtx) {
661
616
  return noUndefined(out);
662
617
  },
663
618
  },
664
- // toy_run_script:运行玩具操控脚本
619
+ // toy_run_script:运行玩具操控脚本
665
620
  {
666
621
  name: 'toy_run_script',
667
- description: '运行你在 workspace/toys/ 下写的一个设备操控脚本(.mjs/.js/.ts)。应使用脚本构建玩具运动的“波形”来控制玩具:不是随机抽取参数,也不是把若干参数和固定时长简单串成阶段表;具体波形由你自行设计。编写或运行前必须先读取 workspace/toys/玩具脚本示例.mjs。\n'
622
+ description: '运行你在 workspace/toys/ 下写的一个设备操控脚本(.mjs/.js/.ts)。应使用脚本构建玩具运动的“波形”来控制玩具:不是随机抽取参数,也不是把若干参数和固定时长简单串成阶段表;具体波形由你自行设计。编写或运行前必须先读取 workspace/toys/玩具脚本示例.mjs。\n'
668
623
  + '脚本侧只需关心设备参数:全局已预加载 toy 对象——await toy.set({ intensity, stroke }) 改变强度/行程、'
669
624
  + 'await toy.sleep(毫秒) 控制节奏、toy.stop() 停止;不接触任何通信细节。'
670
- + '每个玩具脚本必须在自行判断的合适位置调用 await toy.wake({ mood, topic, reason }),请导演感知脚本中的变化并决定是否开口。'
671
- + '脚本与运行日志完全透明可监管:管理台「玩具操控脚本」可查看运行状态与日志(toys/.logs/)。'
672
- + '脚本启动时会清除尚未到期的 toy_control 计时提醒,避免旧控制事件与脚本撞车。'
673
- + '脚本自然结束即终止,结束时设备保持最后的参数继续运行并优先提醒你;中途停可用 stop=runId '
674
- + '或 toy_control stop。脚本运行期间不得直接改用 toy_control 接管;若要改用,必须先显式停止该脚本并确认停止。'
675
- + '每次只有一段脚本在跑,新的脚本调用会接管旧脚本。\n'
676
- + '要先激活设备(用户发分享链接);激活后参考脚本会位于 toys/玩具脚本示例.mjs。',
625
+ + '每个玩具脚本必须在自行判断的合适位置调用 await toy.wake({ mood, topic, reason }),请导演感知脚本中的变化并决定是否开口。'
626
+ + '脚本与运行日志完全透明可监管:管理台「玩具操控脚本」可查看运行状态与日志(toys/.logs/)。'
627
+ + '脚本启动时会清除尚未到期的 toy_control 计时提醒,避免旧控制事件与脚本撞车。'
628
+ + '脚本自然结束即终止,结束时设备保持最后的参数继续运行并优先提醒你;中途停可用 stop=runId '
629
+ + '或 toy_control stop。脚本运行期间不得直接改用 toy_control 接管;若要改用,必须先显式停止该脚本并确认停止。'
630
+ + '每次只有一段脚本在跑,新的脚本调用会接管旧脚本。\n'
631
+ + '要先激活设备(用户发分享链接);激活后参考脚本会位于 toys/玩具脚本示例.mjs。',
677
632
  parameters: {
678
633
  type: 'object',
679
634
  additionalProperties: false,
@@ -714,27 +669,27 @@ export function buildDirectorToolDefs(resolveCtx) {
714
669
  if (!c.roleId) return { ok: false, error: '无角色上下文' };
715
670
  // stop 模式
716
671
  if (typeof args?.stop === 'string' && args.stop.trim()) {
717
- const res = await c.devices.stopScript(args.stop.trim());
672
+ const res = await c.devices.stopScript(args.stop.trim(), c.roleId);
718
673
  return res.ok ? { ok: true, stopped: res.stopped } : { ok: false, error: res.error || '终止失败' };
719
674
  }
720
675
  const ws = typeof c.workspaceOf === 'function' ? await c.workspaceOf() : null;
721
676
  if (!ws) return { ok: false, error: '无角色工作区上下文' };
722
677
  const toysDir = join(ws, 'toys');
723
678
  let names = [];
724
- 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 { /* 目录不存在 */ }
725
680
  let given = typeof args?.script === 'string' ? String(args.script).trim() : '';
726
681
  let scriptPath;
727
- if (given) {
728
- if (given === TOY_REFERENCE_NAME) return { ok: false, error: '玩具脚本示例仅供先阅读参考,请新建自己的脚本后再运行。' };
729
- const p = join(toysDir, given);
730
- if (!existsSync(p)) return { ok: false, error: `toys/${given} 不存在(现有: ${names.join(', ') || '无'})` };
731
- 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;
732
687
  } else {
733
688
  const main = names.find((n) => /^(main|index)\./.test(n)) ?? names[0];
734
689
  if (!main) return { ok: false, error: 'toys/ 下还没有脚本——先用文件工具新建一个 .mjs 再 toy_run_script(参考 templates/sample-toy.mjs)。' };
735
690
  scriptPath = join(toysDir, main);
736
- }
737
- 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;
738
693
  const res = await c.devices.runScript({
739
694
  roleId: c.roleId,
740
695
  scriptPath,
@@ -742,6 +697,7 @@ export function buildDirectorToolDefs(resolveCtx) {
742
697
  httpApiToken: c.httpApiToken,
743
698
  httpApiPath: c.httpApiPath,
744
699
  openid: role?.binding?.openid,
700
+ roleScopedHook: c.target()?.kind === 'direct',
745
701
  reason: args?.reason,
746
702
  });
747
703
  return res.ok
@@ -931,7 +887,7 @@ export function buildMemeToolDefs(resolveCtx) {
931
887
  // meme_send:发送一张表情包
932
888
  {
933
889
  name: 'meme_send',
934
- description: '向当前 QQ 聊天发送一张表情包图片。用 memeId(优先,从 meme_find 拿到)或本地文件路径。'
890
+ description: '向当前聊天发送一张表情包图片。用 memeId(优先,从 meme_find 拿到)或本地文件路径。'
935
891
  + '可带 text 作为配文。发送成功会记录使用时间。',
936
892
  parameters: {
937
893
  type: 'object', additionalProperties: false,
@@ -1160,6 +1116,7 @@ export function registerDirectorTools(agentCtx, sessionId, deps) {
1160
1116
  persona: deps.persona, log: deps.log, workspaceOf: deps.workspaceOf,
1161
1117
  subagents: deps.subagents, llm: deps.llm,
1162
1118
  devices: deps.devices,
1119
+ voice: deps.voice, beginDelivery: deps.beginDelivery,
1163
1120
  });
1164
1121
  for (const def of buildDirectorToolDefs(resolveCtx))
1165
1122
  tools.register(def);
@@ -1177,7 +1134,8 @@ export function registerDirectorTools(agentCtx, sessionId, deps) {
1177
1134
  * (可能为 async:宿主服务可在未命中时按 sessionId 惰性构造依赖)
1178
1135
  * @returns 是否完成注册
1179
1136
  */
1180
- 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) {
1181
1139
  const tools = ctx.tools;
1182
1140
  if (tools === undefined)
1183
1141
  return false;
@@ -1188,21 +1146,35 @@ export function registerStandingTools(ctx, depsFor) {
1188
1146
  const deps = await depsFor(sessionId);
1189
1147
  if (deps === undefined)
1190
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('当前角色无设备操控授权');
1191
1156
  return {
1192
1157
  sessionId,
1193
1158
  api: deps.api, routes: deps.routes,
1194
1159
  target: () => deps.target?.() ?? targetOfSession(sessionId),
1195
1160
  roleId: deps.roleId, httpApiToken: deps.httpApiToken, httpApiPath: deps.httpApiPath,
1196
1161
  persona: deps.persona, log: deps.log, workspaceOf: deps.workspaceOf,
1197
- subagents: deps.subagents, llm: deps.llm,
1162
+ subagents: deps.subagents, llm: deps.llm, sessionPersistence: deps.sessionPersistence,
1198
1163
  devices: deps.devices,
1164
+ identityScope: deps.identityScope,
1165
+ voice: deps.voice, beginDelivery: deps.beginDelivery,
1199
1166
  };
1200
1167
  };
1201
- for (const def of buildQQToolDefs(resolveCtx))
1202
- tools.register(def);
1203
- for (const def of buildDirectorToolDefs(resolveCtx))
1204
- tools.register(def);
1205
- for (const def of buildMemeToolDefs(resolveCtx))
1206
- 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
+ }
1207
1179
  return true;
1208
1180
  }