pygmalion 0.1.8 → 0.1.10

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.
package/src/persona.js CHANGED
@@ -17,13 +17,14 @@
17
17
  * openid 绑定(修 D5):绑定到「角色」而非"任一未绑定账号"。插件按 bot 配置的 roleId
18
18
  * 路由;首聊 openid 自动绑定为拥有者,已绑定则校验一致、不一致拒绝。
19
19
  */
20
- import { mkdir, readFile, readdir, writeFile, rename } from 'node:fs/promises';
20
+ import { mkdir, readFile, readdir, writeFile, rename, rm } from 'node:fs/promises';
21
21
  import { existsSync } from 'node:fs';
22
22
  import { join, dirname } from 'node:path';
23
23
  import { fileURLToPath } from 'node:url';
24
24
  import path from 'node:path';
25
25
  import { homedir } from 'node:os';
26
26
  import { scryptSync, randomBytes, timingSafeEqual, createHash } from 'node:crypto';
27
+ import { deviceDocMarkdown } from './devices/doc.mjs';
27
28
 
28
29
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
29
30
 
@@ -146,7 +147,7 @@ export async function createAccount({ qqNumber, password, displayName }) {
146
147
  const id = String(qqNumber);
147
148
  if (await loadAccount(id)) return null;
148
149
  const { hash, salt } = hashPassword(password ?? '');
149
- const account = { qqNumber: id, passwordHash: hash, salt, roleIds: [] };
150
+ const account = { qqNumber: id, passwordHash: hash, salt, roleIds: [], deviceIds: [] };
150
151
  if (displayName) account.displayName = displayName;
151
152
  await saveAccount(account);
152
153
  return account;
@@ -159,6 +160,82 @@ export async function authenticate(qqNumber, password) {
159
160
  return account;
160
161
  }
161
162
 
163
+ // ---------------------------------------------------------------- 设备库 --
164
+ /**
165
+ * 用户级设备库。设备属于账号(owner=qqNumber),角色通过 persona.devices 勾选授权。
166
+ * 记录:data/devices/<deviceId>.json = { id:'dev-…', owner, kind, alias, createdAt }。
167
+ * 分享 token / 激活态不落盘(单次有效),见 src/devices/manager.mjs。
168
+ */
169
+ export function devicesDir() { return join(dataRoot(), 'devices'); }
170
+ export function devicePath(deviceId) { return join(devicesDir(), `${safeId(deviceId)}.json`); }
171
+ export async function listDevices(owner) {
172
+ const dir = devicesDir();
173
+ let names;
174
+ try { names = await readdir(dir); } catch { return []; }
175
+ const out = [];
176
+ for (const name of names) {
177
+ if (!name.endsWith('.json')) continue;
178
+ const d = await readJson(join(dir, name), null);
179
+ if (d?.id && (!owner || d.owner === owner)) out.push(d);
180
+ }
181
+ return out;
182
+ }
183
+ export async function loadDevice(deviceId) {
184
+ if (!deviceId) return null;
185
+ return await readJson(devicePath(deviceId), null);
186
+ }
187
+ /** 建设备并回写账号 deviceIds。kind v1 仅 'monsterparty'。 */
188
+ export async function createDevice({ owner, alias, kind = 'monsterparty' }) {
189
+ if (!owner || !String(alias ?? '').trim()) return null;
190
+ const id = `dev-${randomBytes(8).toString('hex')}`;
191
+ const device = { id, owner, kind, alias: String(alias).trim(), createdAt: Date.now() };
192
+ await atomicWriteJson(devicePath(id), device);
193
+ const account = await loadAccount(owner);
194
+ if (account) {
195
+ account.deviceIds = [...(account.deviceIds ?? []), id];
196
+ await saveAccount(account);
197
+ }
198
+ return device;
199
+ }
200
+ /**
201
+ * 删设备:移除记录、从 owner 账号 deviceIds 摘除、并遍历 owner 各角色从 persona.devices
202
+ * 摘引用。返回 { removed, roleIds }(roleIds=受影响角色,供调用方 disposeRole + 重渲记忆)。
203
+ */
204
+ export async function deleteDevice(deviceId) {
205
+ const device = await loadDevice(deviceId);
206
+ if (!device) return { removed: false, roleIds: [] };
207
+ await rm(devicePath(deviceId), { force: true });
208
+ const account = await loadAccount(device.owner);
209
+ if (account) {
210
+ account.deviceIds = (account.deviceIds ?? []).filter((d) => d !== deviceId);
211
+ await saveAccount(account);
212
+ }
213
+ const roleIds = [];
214
+ for (const role of await listRoles()) {
215
+ if (role.persona?.owner !== device.owner) continue;
216
+ const list = Array.isArray(role.persona.devices) ? role.persona.devices : [];
217
+ if (!list.includes(deviceId)) continue;
218
+ role.persona.devices = list.filter((d) => d !== deviceId);
219
+ await saveRoleField(role.roleId, 'persona', role.persona);
220
+ roleIds.push(role.roleId);
221
+ }
222
+ return { removed: true, roleIds };
223
+ }
224
+ /** 角色授权设备的文档(memory/设备.md 内容);无授权合法设备 → null。 */
225
+ export async function renderDeviceDoc(role) {
226
+ const persona = role?.persona;
227
+ const ids = Array.isArray(persona?.devices) ? persona.devices : [];
228
+ if (!ids.length) return null;
229
+ const owner = persona.owner;
230
+ const parts = [];
231
+ for (const id of ids) {
232
+ const dev = await loadDevice(id);
233
+ if (!dev || dev.owner !== owner) continue; // 只渲染存在且属于本账号的
234
+ parts.push(deviceDocMarkdown(dev));
235
+ }
236
+ return parts.length ? parts.join('\n\n') : null;
237
+ }
238
+
162
239
  // ---------------------------------------------------------------- session --
163
240
  /** 内存登录会话(Phase 5 管理网页接 httpOnly cookie)。 */
164
241
  const sessions = new Map(); // token -> { accountId, expiresAt }
@@ -194,7 +271,8 @@ export async function loadRole(roleId) {
194
271
  model: { ...DEFAULT_MODEL, ...(await roleJson(roleId, 'model.json', {})) },
195
272
  proactive: { ...DEFAULT_PROACTIVE, ...(await roleJson(roleId, 'proactive.json', {})) },
196
273
  binding: await roleJson(roleId, 'binding.json', {}),
197
- state: await roleJson(roleId, 'state.json', {}),
274
+ state: await roleJson(roleId, 'state.json', {}),
275
+ voice: await roleJson(roleId, 'voice/mimo.json', {}),
198
276
  workspace: roleWorkspace(roleId),
199
277
  };
200
278
  }
@@ -385,6 +463,14 @@ export async function syncRoleMemory(role) {
385
463
  if (role.persona) {
386
464
  await atomicWrite(join(memory, '人物设定.md'), (personaMarkdown(role.persona) ?? '') + '\n');
387
465
  }
466
+ // 设备文档:角色授权设备 → memory/设备.md(preset 开场读);无授权 → 删除(撤选不残留)。
467
+ const devFile = join(memory, '设备.md');
468
+ const devDoc = await renderDeviceDoc(role);
469
+ if (devDoc) {
470
+ await atomicWrite(devFile, devDoc + '\n');
471
+ } else {
472
+ try { await rm(devFile, { force: true }); } catch { /* ignore */ }
473
+ }
388
474
  // 特殊记忆首次就位(已存在则保留 dsh 的编辑,不覆盖)。
389
475
  const taFile = join(memory, '关于TA.md');
390
476
  const taExists = await readFile(taFile, 'utf8').then(() => true).catch(() => false);
@@ -62,7 +62,7 @@ export function extractUserMessages(events) {
62
62
  }
63
63
 
64
64
  /** 模型侧上下文行(固定结构,非用户原话):[时间线] 时间戳行、[生活脚本] 非零提示行、[身份提醒] 边界提示行、[已下载附件:…] 行。 */
65
- const CONTEXT_LINE = /^\[(?:时间线|生活脚本|身份提醒)\]/;
65
+ const CONTEXT_LINE = /^\[(?:时间线|生活脚本|身份提醒|设备)\]/;
66
66
 
67
67
  /** 剥离模型侧包装([时间线]…、[生活脚本]…、[已下载附件:…]、[引用消息开始]…),只留用户原话。 */
68
68
  export function cleanUserText(raw) {
@@ -131,7 +131,10 @@ export function extractMessages(events) {
131
131
  } else if (ev?.type === 'tool/call' && ev.data?.name === 'director_send') {
132
132
  try {
133
133
  const args = JSON.parse(ev.data.arguments ?? '{}');
134
- for (const m of Array.isArray(args.messages) ? args.messages : []) push('character', ev.time, m);
134
+ for (const m of Array.isArray(args.messages) ? args.messages : []) {
135
+ if (typeof m === 'string') push('character', ev.time, m);
136
+ else if (m && typeof m.text === 'string') push('character', ev.time, m.type === 'voice' ? `[语音] ${m.text}` : m.text);
137
+ }
135
138
  } catch { /* skip malformed */ }
136
139
  }
137
140
  }
@@ -9,12 +9,13 @@ import { attachSessionToCwdWorkspace } from './dsh-bookkeeping.js';
9
9
  * 登记」两处复用。
10
10
  */
11
11
  export function buildSessionDeps(deps, sessionId) {
12
- const { api, routes, persona, roleId, httpApiToken, httpApiPath, log, subagents, llm } = deps;
12
+ const { api, routes, persona, roleId, httpApiToken, httpApiPath, log, subagents, llm, devices } = deps;
13
13
  return {
14
14
  api, routes,
15
15
  target: () => routes.get(sessionId)?.target ?? targetOfSession(sessionId),
16
16
  roleId, httpApiToken, httpApiPath, persona, log,
17
17
  subagents, llm,
18
+ devices,
18
19
  workspaceOf: roleId !== undefined && persona !== undefined
19
20
  ? async () => persona.roleWorkspace(roleId)
20
21
  : undefined,
@@ -79,6 +80,7 @@ export function createSetupAgent(deps) {
79
80
  persona,
80
81
  log,
81
82
  subagents: deps.subagents, llm: deps.llm,
83
+ devices: deps.devices,
82
84
  workspaceOf: roleId !== undefined && persona !== undefined
83
85
  ? async () => persona.roleWorkspace(roleId)
84
86
  : undefined,
package/src/tools.js CHANGED
@@ -6,7 +6,8 @@ import { findLifeScript, listLifeScripts, startLifeScript, stopLifeScript, readL
6
6
  import { sessionFileFor } from './active-session.js';
7
7
  import { refreshRawRecordFromSession, charLabelOf } from './memory-write.js';
8
8
  import { saveMeme, findMemes, memeFileFor, updateMeme, recordMemeUsed, downloadPageImagesToCollectDir } from './memebox.js';
9
- import { resolveVisionConfig, collectAndClassify, withMemeLock, readImageBySubagent, archiveImageBySubagent, memeTrace } from './meme-worker.js';
9
+ import { resolveVisionConfig, collectAndClassify, withMemeLock, readImageBySubagent, archiveImageBySubagent, memeTrace } from './meme-worker.js';
10
+ import { synthesizeMiMoVoice } from './voice-mimo.js';
10
11
 
11
12
  const IMAGE_EXTS = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.svg', '.ico']);
12
13
  const VOICE_EXTS = new Set(['.wav', '.mp3', '.silk', '.amr', '.ogg', '.flac', '.aac', '.m4a']);
@@ -182,10 +183,18 @@ export function buildDirectorToolDefs(resolveCtx) {
182
183
  type: 'object',
183
184
  additionalProperties: false,
184
185
  properties: {
185
- messages: {
186
- type: 'array',
187
- items: { type: 'string' },
188
- description: '要逐条发送的聊天消息列表;空数组或省略 = 不发送(沉默)。',
186
+ messages: {
187
+ type: 'array',
188
+ items: { oneOf: [
189
+ { type: 'string' },
190
+ { type: 'object', additionalProperties: false, required: ['type', 'text'], properties: {
191
+ type: { type: 'string', enum: ['text', 'voice'] },
192
+ text: { type: 'string', description: '发送文本或朗读台词。' },
193
+ scene: { type: 'string', description: '仅 voice:本条语音的完整情景与情绪动机。' },
194
+ direction: { type: 'string', description: '仅 voice:一句整体表演方向,不编排变化时机。' },
195
+ } },
196
+ ] },
197
+ description: '按顺序发送的消息;字符串兼容旧文本格式。voice 由角色已配置的 MiMo 音色合成并发送。空数组或省略 = 不发送。',
189
198
  },
190
199
  reawake: {
191
200
  oneOf: [{ type: 'number' }, { type: 'string' }],
@@ -204,7 +213,7 @@ export function buildDirectorToolDefs(resolveCtx) {
204
213
  schema: {
205
214
  type: 'object',
206
215
  additionalProperties: false,
207
- properties: { ok: { type: 'boolean' }, sent: { type: 'number' }, reawake: { type: 'number' }, error: { type: 'string' } },
216
+ properties: { ok: { type: 'boolean' }, sent: { type: 'number' }, textSent: { type: 'number' }, voiceSent: { type: 'number' }, failedAt: { type: 'number' }, reawake: { type: 'number' }, error: { type: 'string' } },
208
217
  required: ['ok', 'sent'],
209
218
  },
210
219
  render: (_args, value) => [
@@ -213,32 +222,42 @@ export function buildDirectorToolDefs(resolveCtx) {
213
222
  : `发送失败: ${value.error ?? '?'}` },
214
223
  ],
215
224
  },
216
- timeoutMs: 60_000,
225
+ timeoutMs: 360_000,
217
226
  async execute(args, exec) {
218
227
  const c = await resolveCtx(args, exec);
219
- const raw = Array.isArray(args?.messages) ? args.messages : [];
220
- const messages = raw.map((s) => String(s ?? '').trim()).filter((s) => s.length > 0);
221
- const sent = [];
228
+ const raw = Array.isArray(args?.messages) ? args.messages : [];
229
+ const messages = raw.map((item) => typeof item === 'string'
230
+ ? { type: 'text', text: item.trim() }
231
+ : { type: item?.type === 'voice' ? 'voice' : 'text', text: String(item?.text ?? '').trim(), scene: String(item?.scene ?? '').trim(), direction: String(item?.direction ?? '').trim() })
232
+ .filter((item) => item.text.length > 0);
233
+ const sent = [];
222
234
  if (messages.length > 0) {
223
235
  const record = c.routes?.get(c.sessionId);
224
236
  const passive = record
225
237
  ? c.routes.consumePassive(c.sessionId, record.target.kind === 'group' ? 5 * 60 * 1000 : 30 * 60 * 1000, 4)
226
238
  : undefined;
227
- for (const msg of messages) {
228
- try {
229
- await c.api.sendText(c.target(), msg, passive);
230
- sent.push(msg);
239
+ for (const msg of messages) {
240
+ try {
241
+ if (msg.type === 'voice') {
242
+ if (!c.roleId) throw new Error('当前会话没有角色语音配置');
243
+ const audio = await synthesizeMiMoVoice({ roleId: c.roleId, text: msg.text, scene: msg.scene, direction: msg.direction });
244
+ try { await c.api.sendMedia(c.target(), 'voice', audio.file, { passiveMsgId: passive }); }
245
+ finally { await audio.cleanup(); }
246
+ } else {
247
+ await c.api.sendText(c.target(), msg.text, passive);
248
+ }
249
+ sent.push(msg);
231
250
  }
232
251
  catch (error) {
233
252
  return {
234
- ok: false, sent: sent.length,
253
+ ok: false, sent: sent.length, failedAt: sent.length,
235
254
  error: error instanceof Error ? error.message : String(error),
236
255
  };
237
256
  }
238
257
  }
239
258
  // 日期层记忆:角色消息发出后延迟从活跃会话 session log 提取写原始记录
240
259
  // (等 dsh 把 director_send 工具调用落盘;仅 c2c 拥有者会话)。
241
- if (sent.length > 0 && c.target()?.kind === 'c2c') {
260
+ if (sent.length > 0 && c.target()?.kind === 'c2c') {
242
261
  const workspace = c.workspaceOf
243
262
  ? await c.workspaceOf()
244
263
  : (c.persona && c.roleId ? c.persona.roleWorkspace(c.roleId) : undefined);
@@ -258,7 +277,7 @@ export function buildDirectorToolDefs(resolveCtx) {
258
277
  // reawake:正数分钟 → 写角色 state.rewake 队列;'none'/缺省 → 不安排。
259
278
  const ra = args?.reawake;
260
279
  if (ra === undefined || ra === null || ra === 'none' || ra === 'NONE')
261
- return { ok: true, sent: sent.length };
280
+ return { ok: true, sent: sent.length, textSent: sent.filter((m) => m.type === 'text').length, voiceSent: sent.filter((m) => m.type === 'voice').length };
262
281
  const minutes = typeof ra === 'number' ? ra : Number(String(ra).trim());
263
282
  if (Number.isFinite(minutes) && minutes > 0) {
264
283
  const rw = c.roleId && c.persona?.scheduleRewake
@@ -447,6 +466,206 @@ export function buildDirectorToolDefs(resolveCtx) {
447
466
  : { ok: false, error: res.error || '启动失败' };
448
467
  },
449
468
  },
469
+ // toy_status:查询角色可用设备状态
470
+ {
471
+ name: 'toy_status',
472
+ description: '查询当前角色已授权可用设备的状态:是否已激活(ta 是否发过分享链接)、当前运行状态'
473
+ + '(controller/last 参数/是否有脚本在跑)。需要操作设备前可先调用确认。',
474
+ parameters: {
475
+ type: 'object',
476
+ additionalProperties: false,
477
+ properties: {},
478
+ },
479
+ output: {
480
+ schema: {
481
+ type: 'object',
482
+ additionalProperties: false,
483
+ properties: {
484
+ ok: { type: 'boolean' },
485
+ devices: { type: 'array', items: { type: 'object' } },
486
+ error: { type: 'string' },
487
+ },
488
+ required: ['ok'],
489
+ },
490
+ render: (_args, value) => {
491
+ const v = value;
492
+ let text;
493
+ if (!v?.ok) text = `toy_status 失败: ${v?.error ?? '?'}`;
494
+ else if (!v.devices?.length) text = '该角色未配置可用设备。';
495
+ else {
496
+ const lines = v.devices.map((d) => `- ${d.alias}(${d.kind}):${d.activated ? '已激活' : '未激活——需 ta 发分享链接'}`
497
+ + (d.activated ? ` | 运行:${d.controller}${d.last ? ` 参数=${d.last.intensity !== 0 || d.last.stroke ? JSON.stringify(d.last) : ''}` : ''}${d.runId ? ` | 脚本=${d.runId}` : ''}` : ''));
498
+ text = ['可用设备:'].concat(lines).join('\n');
499
+ }
500
+ return [{ type: 'text', text }];
501
+ },
502
+ },
503
+ timeoutMs: 60_000,
504
+ async execute(_args, exec) {
505
+ const c = await resolveCtx(_args, exec);
506
+ if (!c.devices) return { ok: false, error: '设备服务不可用' };
507
+ if (!c.roleId) return { ok: false, error: '无角色上下文' };
508
+ return await c.devices.status(c.roleId);
509
+ },
510
+ },
511
+ // toy_control:定时/即时操控设备(工具调用模式)
512
+ {
513
+ name: 'toy_control',
514
+ description: '操控当前角色可用的玩具设备(行程+强度)。需要 ta 已发过一条新鲜分享链接(激活),否则会提示先请 ta 发。\n'
515
+ + '参数:intensity 强度 0-100;stroke 行程范围(用两个边界,取值 0/33/66/100,如 "0,100"=L1~L3 全行程往复、'
516
+ + '"0,66"=L1~L2 区间、"0,0"=停住;也可写区间名 "L1,L2");seconds 本次操作的时长(秒)。\n'
517
+ + '计时语义:到点后设备保持当前参数继续运行,系统会提醒你计时结束,可再次调用本工具调整或 stop。'
518
+ + '设备无自动停止——由你决定何时停(ta 要求停时必须停);停用 stop:true。\n'
519
+ + '注意:新一次调用会接管当前计时/脚本;单台设备一次只有一个在跑。',
520
+ parameters: {
521
+ type: 'object',
522
+ additionalProperties: false,
523
+ properties: {
524
+ device: { type: 'string', description: '可选:设备名/deviceId(角色只勾了一台可省)。' },
525
+ stroke: { type: 'string', description: '行程范围,如 "0,100"/"33,66"/"L1,L2"/"0,0"。' },
526
+ intensity: { type: 'number', description: '强度 0-100。' },
527
+ seconds: { type: 'number', description: '本次时长(秒);省略=立即设定不设计时。' },
528
+ stop: { type: 'boolean', description: 'true=停止设备(清计时/脚本并强度归零)。' },
529
+ },
530
+ },
531
+ output: {
532
+ schema: {
533
+ type: 'object',
534
+ additionalProperties: false,
535
+ properties: {
536
+ ok: { type: 'boolean' },
537
+ state: { type: 'object' },
538
+ seconds: { type: 'number' },
539
+ error: { type: 'string' },
540
+ },
541
+ required: ['ok'],
542
+ },
543
+ render: (_args, value) => {
544
+ const v = value;
545
+ let text;
546
+ if (!v?.ok) {
547
+ const err = v?.error ?? '?';
548
+ text = `toy_control 失败: ${err}${err.includes('激活') || err.includes('分享链接') ? '(让 ta 发一条新鲜分享链接即可)' : ''}`;
549
+ } else {
550
+ const s = v.state;
551
+ const last = s?.last;
552
+ const paramText = last ? `强度 ${last.intensity}${last.stroke ? `、行程 ${last.stroke.join(',')}` : ''}` : '无参数';
553
+ if (s?.controller === 'idle' && !last) text = '已停止设备。';
554
+ else text = v.seconds
555
+ ? `设备已设定,持续 ${v.seconds}s:${paramText}(到点保持参数并提醒你)`
556
+ : `设备已设定:${paramText}(无计时;停用 toy_control stop)`;
557
+ }
558
+ return [{ type: 'text', text }];
559
+ },
560
+ },
561
+ timeoutMs: 60_000,
562
+ async execute(args, exec) {
563
+ const c = await resolveCtx(args, exec);
564
+ if (!c.devices) return { ok: false, error: '设备服务不可用' };
565
+ if (!c.roleId) return { ok: false, error: '无角色上下文' };
566
+ if (args?.stop !== true && args?.intensity === undefined && args?.stroke === undefined) {
567
+ return { ok: false, error: '需提供 intensity 或 stroke(或 stop:true 停止)' };
568
+ }
569
+ const r = await c.devices.applyFromTool({
570
+ roleId: c.roleId,
571
+ deviceId: typeof args?.device === 'string' && args.device ? args.device : undefined,
572
+ intensity: args?.intensity,
573
+ stroke: args?.stroke,
574
+ seconds: args?.seconds,
575
+ stop: args?.stop === true,
576
+ });
577
+ if (!r?.ok) return { ok: false, error: r?.error || '失败' };
578
+ const out = { ok: true, state: r.state };
579
+ if (Number(args?.seconds) > 0) out.seconds = Number(args.seconds);
580
+ return noUndefined(out);
581
+ },
582
+ },
583
+ // toy_run_script:运行编排脚本(脚本模式)
584
+ {
585
+ name: 'toy_run_script',
586
+ description: '运行你在 workspace/toys/ 下写的一个设备操控脚本(.mjs/.js/.ts)。脚本是自由程序,运作方式完全由你设计:'
587
+ + '可以是编排好的动作流程,也可以随时间、对话或 ta 的反馈而变化、循环、分段推进等,随你创造。\n'
588
+ + '脚本侧只需关心设备参数:全局已预加载 toy 对象——await toy.set({ intensity, stroke }) 改变强度/行程、'
589
+ + 'await toy.sleep(毫秒) 控制节奏、toy.stop() 停止;不接触任何通信细节。'
590
+ + '合适时机可 await toy.wake({ mood, topic, reason }) 请导演开口(可说可静默)。'
591
+ + '脚本与运行日志完全透明可监管:管理台「玩具操控脚本」可查看运行状态与日志(toys/.logs/)。'
592
+ + '脚本自然结束即终止,结束时设备保持最后的参数继续运行并提醒你;中途停可用 stop=runId '
593
+ + '或 toy_control stop。每次只有一段脚本在跑,新的调用会接管。\n'
594
+ + '要先激活设备(ta 发分享链接)。templates/sample-toy.mjs 只是语法示例,勿照搬套路。',
595
+ parameters: {
596
+ type: 'object',
597
+ additionalProperties: false,
598
+ properties: {
599
+ script: { type: 'string', description: 'toys/ 下脚本文件名(省略找 main.*/index.*)。' },
600
+ reason: { type: 'string', description: '可选:本次启动/终止的缘由(记录)。' },
601
+ stop: { type: 'string', description: '可选:终止运行中的脚本 runId(提供时不再启动新脚本)。' },
602
+ },
603
+ },
604
+ output: {
605
+ schema: {
606
+ type: 'object',
607
+ additionalProperties: false,
608
+ properties: {
609
+ ok: { type: 'boolean' },
610
+ runId: { type: 'string' },
611
+ pid: { type: 'number' },
612
+ startedAt: { type: 'number' },
613
+ script: { type: 'string' },
614
+ stopped: { type: 'string' },
615
+ error: { type: 'string' },
616
+ },
617
+ required: ['ok'],
618
+ },
619
+ render: (_args, value) => {
620
+ const v = value;
621
+ let text;
622
+ if (!v?.ok) text = `toy_run_script 失败: ${v?.error ?? '?'}`;
623
+ else if (v.stopped) text = `已终止脚本 runId=${v.stopped}`;
624
+ else text = `toy 脚本已启动: ${v.script ?? ''}(runId=${v.runId}, pid=${v.pid})\n脚本在后台运行,自然结束=终止并保持最后参数;可用 toy_run_script stop=${v.runId} 或 toy_control stop 终止。`;
625
+ return [{ type: 'text', text }];
626
+ },
627
+ },
628
+ timeoutMs: 60_000,
629
+ async execute(args, exec) {
630
+ const c = await resolveCtx(args, exec);
631
+ if (!c.devices) return { ok: false, error: '设备服务不可用' };
632
+ if (!c.roleId) return { ok: false, error: '无角色上下文' };
633
+ // stop 模式
634
+ if (typeof args?.stop === 'string' && args.stop.trim()) {
635
+ const res = await c.devices.stopScript(args.stop.trim());
636
+ return res.ok ? { ok: true, stopped: res.stopped } : { ok: false, error: res.error || '终止失败' };
637
+ }
638
+ const ws = typeof c.workspaceOf === 'function' ? await c.workspaceOf() : null;
639
+ if (!ws) return { ok: false, error: '无角色工作区上下文' };
640
+ const toysDir = join(ws, 'toys');
641
+ let names = [];
642
+ try { names = (await readdir(toysDir)).filter((n) => /\.(mjs|js|ts)$/.test(n)); } catch { /* 目录不存在 */ }
643
+ let given = typeof args?.script === 'string' ? String(args.script).trim() : '';
644
+ let scriptPath;
645
+ if (given) {
646
+ const p = join(toysDir, given);
647
+ if (!existsSync(p)) return { ok: false, error: `toys/${given} 不存在(现有: ${names.join(', ') || '无'})` };
648
+ scriptPath = p;
649
+ } else {
650
+ const main = names.find((n) => /^(main|index)\./.test(n)) ?? names[0];
651
+ if (!main) return { ok: false, error: 'toys/ 下还没有脚本——先用文件工具新建一个 .mjs 再 toy_run_script(参考 templates/sample-toy.mjs)。' };
652
+ scriptPath = join(toysDir, main);
653
+ }
654
+ const role = c.persona && c.roleId ? await c.persona.loadRole(c.roleId).catch(() => null) : null;
655
+ const res = await c.devices.runScript({
656
+ roleId: c.roleId,
657
+ scriptPath,
658
+ workspace: ws,
659
+ httpApiToken: c.httpApiToken,
660
+ httpApiPath: c.httpApiPath,
661
+ openid: role?.binding?.openid,
662
+ reason: args?.reason,
663
+ });
664
+ return res.ok
665
+ ? { ok: true, runId: res.runId, pid: res.pid, startedAt: res.startedAt, script: res.script }
666
+ : { ok: false, error: res.error || '启动失败' };
667
+ },
668
+ },
450
669
  ];
451
670
  }
452
671
 
@@ -857,6 +1076,7 @@ export function registerDirectorTools(agentCtx, sessionId, deps) {
857
1076
  roleId: deps.roleId, httpApiToken: deps.httpApiToken, httpApiPath: deps.httpApiPath,
858
1077
  persona: deps.persona, log: deps.log, workspaceOf: deps.workspaceOf,
859
1078
  subagents: deps.subagents, llm: deps.llm,
1079
+ devices: deps.devices,
860
1080
  });
861
1081
  for (const def of buildDirectorToolDefs(resolveCtx))
862
1082
  tools.register(def);
@@ -892,6 +1112,7 @@ export function registerStandingTools(ctx, depsFor) {
892
1112
  roleId: deps.roleId, httpApiToken: deps.httpApiToken, httpApiPath: deps.httpApiPath,
893
1113
  persona: deps.persona, log: deps.log, workspaceOf: deps.workspaceOf,
894
1114
  subagents: deps.subagents, llm: deps.llm,
1115
+ devices: deps.devices,
895
1116
  };
896
1117
  };
897
1118
  for (const def of buildQQToolDefs(resolveCtx))
@@ -0,0 +1,95 @@
1
+ /** MiMo VoiceClone:角色私有配置、参考音频与一次性合成文件。 */
2
+ import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
3
+ import { existsSync } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import * as persona from './persona.js';
7
+
8
+ const BASE = 'https://api.xiaomimimo.com/v1';
9
+ const MODEL = 'mimo-v2.5-tts-voiceclone';
10
+ const MAX_REFERENCE_BYTES = Math.floor((10 * 1024 * 1024 * 3) / 4);
11
+ const FALLBACK = '请保持咬字清晰。情绪、语气、声调和音量应依据角色、场景和台词自然、连贯地变化。';
12
+
13
+ function voiceDir(roleId) { return join(persona.roleDir(roleId), 'voice'); }
14
+ function configPath(roleId) { return join(voiceDir(roleId), 'mimo.json'); }
15
+ function referencePath(roleId, ext = 'wav') { return join(voiceDir(roleId), `reference.${ext}`); }
16
+ function clean(value, max = 2000) { return String(value ?? '').trim().slice(0, max); }
17
+
18
+ export async function loadVoiceConfig(roleId) {
19
+ const role = await persona.loadRole(roleId);
20
+ if (!role) return null;
21
+ const value = await readFile(configPath(roleId), 'utf8').then(JSON.parse).catch(() => ({}));
22
+ const ref = value.reference && existsSync(referencePath(roleId, value.reference.ext)) ? value.reference : null;
23
+ return { enabled: value.enabled === true, apiBase: clean(value.apiBase) || BASE, model: clean(value.model) || MODEL,
24
+ apiKey: clean(value.apiKey, 500), rolePrompt: clean(value.rolePrompt), reference: ref };
25
+ }
26
+
27
+ export async function saveVoiceConfig(roleId, patch) {
28
+ const current = await loadVoiceConfig(roleId);
29
+ if (!current) throw new Error('角色不存在');
30
+ const next = {
31
+ enabled: patch?.enabled === undefined ? current.enabled : patch.enabled === true,
32
+ apiBase: clean(patch?.apiBase) || current.apiBase || BASE,
33
+ model: clean(patch?.model) || current.model || MODEL,
34
+ apiKey: patch?.apiKey === undefined || clean(patch.apiKey, 500) === '' ? current.apiKey : clean(patch.apiKey, 500),
35
+ rolePrompt: patch?.rolePrompt === undefined ? current.rolePrompt : clean(patch.rolePrompt),
36
+ reference: current.reference,
37
+ };
38
+ await mkdir(voiceDir(roleId), { recursive: true });
39
+ await persona.atomicWrite(configPath(roleId), JSON.stringify(next, null, 2));
40
+ return publicVoiceConfig(next);
41
+ }
42
+
43
+ export async function saveReferenceAudio(roleId, { data, mime, name }) {
44
+ const cfg = await loadVoiceConfig(roleId);
45
+ if (!cfg) throw new Error('角色不存在');
46
+ const normalized = String(mime ?? '').toLowerCase();
47
+ const ext = normalized === 'audio/mpeg' || normalized === 'audio/mp3' ? 'mp3' : normalized === 'audio/wav' || normalized === 'audio/x-wav' ? 'wav' : null;
48
+ if (!ext) throw new Error('参考音频只支持 WAV 或 MP3');
49
+ const bytes = Buffer.from(String(data ?? ''), 'base64');
50
+ if (!bytes.length || bytes.length > MAX_REFERENCE_BYTES) throw new Error('参考音频过大(Base64 编码后不得超过 10MB)');
51
+ await mkdir(voiceDir(roleId), { recursive: true });
52
+ if (cfg.reference?.ext && cfg.reference.ext !== ext) await rm(referencePath(roleId, cfg.reference.ext), { force: true });
53
+ await writeFile(referencePath(roleId, ext), bytes);
54
+ const next = { ...cfg, reference: { ext, name: clean(name, 180) || `reference.${ext}`, bytes: bytes.length, updatedAt: Date.now() } };
55
+ await persona.atomicWrite(configPath(roleId), JSON.stringify(next, null, 2));
56
+ return publicVoiceConfig(next);
57
+ }
58
+
59
+ export function publicVoiceConfig(config) {
60
+ return { enabled: config?.enabled === true, configured: Boolean(config?.apiKey), apiBase: config?.apiBase || BASE,
61
+ model: config?.model || MODEL, rolePrompt: config?.rolePrompt || '', reference: config?.reference || null };
62
+ }
63
+
64
+ export function buildVoiceDirectorPrompt({ rolePrompt, scene, direction }) {
65
+ return [`角色:${clean(rolePrompt, 1200) || '保持参考音频中的角色音色。'}`,
66
+ `场景:${clean(scene, 1600) || '根据台词自然表达。'}`,
67
+ `指导:${clean(direction, 800) || '自然表达当前情绪。'}`,
68
+ FALLBACK].join('\n');
69
+ }
70
+
71
+ export async function synthesizeMiMoVoice({ roleId, text, scene, direction }) {
72
+ const cfg = await loadVoiceConfig(roleId);
73
+ if (!cfg?.enabled) throw new Error('该角色未启用 MiMo 语音');
74
+ if (!cfg.apiKey) throw new Error('该角色尚未配置 MiMo API Key');
75
+ if (!cfg.reference) throw new Error('该角色尚未上传参考音频');
76
+ const spoken = clean(text, 5000);
77
+ if (!spoken) throw new Error('语音台词不能为空');
78
+ const reference = await readFile(referencePath(roleId, cfg.reference.ext));
79
+ const mime = cfg.reference.ext === 'mp3' ? 'audio/mpeg' : 'audio/wav';
80
+ const res = await fetch(`${cfg.apiBase.replace(/\/$/, '')}/chat/completions`, {
81
+ method: 'POST', headers: { authorization: `Bearer ${cfg.apiKey}`, 'content-type': 'application/json' },
82
+ body: JSON.stringify({ model: cfg.model, messages: [
83
+ { role: 'user', content: buildVoiceDirectorPrompt({ rolePrompt: cfg.rolePrompt, scene, direction }) },
84
+ { role: 'assistant', content: spoken },
85
+ ], audio: { format: 'wav', voice: `data:${mime};base64,${reference.toString('base64')}` } }),
86
+ signal: AbortSignal.timeout(300_000),
87
+ });
88
+ const raw = await res.text(); let json; try { json = JSON.parse(raw); } catch { json = {}; }
89
+ const audio = json?.choices?.[0]?.message?.audio?.data;
90
+ if (!res.ok || typeof audio !== 'string') throw new Error(`MiMo 合成失败(HTTP ${res.status}):${json?.error?.message || json?.message || '无音频返回'}`);
91
+ const dir = await mkdtemp(join(tmpdir(), 'pygmalion-mimo-'));
92
+ const file = join(dir, 'voice.wav');
93
+ await writeFile(file, Buffer.from(audio, 'base64'));
94
+ return { file, cleanup: () => rm(dir, { recursive: true, force: true }) };
95
+ }
package/src/wakeup.js CHANGED
@@ -150,11 +150,12 @@ export async function archiveWakeup(deps, params) {
150
150
  }
151
151
 
152
152
  export async function wakeupSession(deps, params) {
153
- const { target, reason, memoryHint, force, kind, event, mood, topic } = params;
153
+ const { target, reason, memoryHint, force, kind, event, mood, topic, contextText } = params;
154
154
  const thread = deps.threads.current(targetKey(target));
155
155
  const sessionId = effectiveSessionId(target, thread, deps.botId);
156
156
 
157
157
  // Collision detection: do not barge into an active / recent conversation.
158
+ // 设备内部信号(计时结束/脚本结束)不走撞车——它已是当前对话语境的一部分,由 dsh 决定开口与否。
158
159
  if (force !== true) {
159
160
  const lastAt = typeof deps.activityAt === 'function'
160
161
  ? deps.activityAt(sessionId)
@@ -187,7 +188,9 @@ export async function wakeupSession(deps, params) {
187
188
  }
188
189
 
189
190
  let text;
190
- if (kind === 'life') text = buildLifeWindowContext({ reason, personaName, hasLifeScript });
191
+ if (typeof contextText === 'string' && contextText.length > 0) {
192
+ text = contextText; // 调用方已构造完整情境(如设备事件)
193
+ } else if (kind === 'life') text = buildLifeWindowContext({ reason, personaName, hasLifeScript });
191
194
  else if (kind === 'script-hook') text = buildScriptEventContext({ event, mood, topic, reason, personaName });
192
195
  else text = buildWakeupContext({ reason, memoryHint, personaName });
193
196
  deps.log?.info?.('pygmalion wakeup: waking %s (%s)', sessionId, reason ?? '(default)');