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/web-server.js CHANGED
@@ -20,7 +20,7 @@
20
20
  * GET /api/me/roles/<roleId> → 完整角色(persona/model/proactive/binding/bot/脚本状态)
21
21
  * PUT /api/me/roles/<roleId> { persona?, model?, proactive? }
22
22
  * DELETE /api/me/roles/<roleId> → 级联删除该角色的机器人
23
- * PUT /api/me/roles/<roleId>/bot { qqAppId, qqSecret?, sandbox?, withinChatWindowMs?, streaming? }
23
+ * PUT /api/me/roles/<roleId>/bot { qqAppId, qqSecret?, sandbox?, withinChatWindowMs?, streaming?, enabled? }
24
24
  * DELETE /api/me/roles/<roleId>/bot
25
25
  * POST /api/me/roles/<roleId>/reset-binding
26
26
  * GET /api/me/roles/<roleId>/life → 脚本监管:manifest + logs + backups + running 清单
@@ -29,19 +29,20 @@
29
29
  * POST /api/me/roles/<roleId>/life/stop → 终止一个运行中脚本(body: { runId })
30
30
  */
31
31
  import { createServer } from 'node:http';
32
- import { readFile, readdir } from 'node:fs/promises';
32
+ import { readFile, readdir } from 'node:fs/promises';
33
33
  import { existsSync } from 'node:fs';
34
34
  import { join, extname } from 'node:path';
35
35
  import { fileURLToPath } from 'node:url';
36
36
  import path from 'node:path';
37
- import { listLifeScripts, listRunningLifeScripts, stopLifeScript, recoverLifeScripts, pruneDeadLifeScripts } from './agent-life.js';
37
+ import { listLifeScripts, listRunningLifeScripts, stopLifeScript, stopLifeScripts, recoverLifeScripts, pruneDeadLifeScripts } from './agent-life.js';
38
38
  import { roleUsesCustomProvider, roleUsesCustomSubagentApi } from './llm-provider.js';
39
- import { listMemes, saveMeme, updateMeme, deleteMeme, memeFileFor } from './memebox.js';
39
+ import { listMemes, saveMeme, updateMeme, deleteMeme, memeFileFor } from './memebox.js';
40
+ import { loadVoiceConfig, publicVoiceConfig, saveReferenceAudio, saveVoiceConfig } from './voice-mimo.js';
40
41
 
41
42
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
42
43
  const PUBLIC_DIR = join(__dirname, 'web-public');
43
44
  const COOKIE_NAME = 'pygmalion_sid';
44
- const BODY_LIMIT = 1 * 1024 * 1024;
45
+ const BODY_LIMIT = 12 * 1024 * 1024;
45
46
  const LOGIN_MAX_FAILS = 5;
46
47
  const LOGIN_LOCK_MS = 15 * 60 * 1000;
47
48
  const MIME = {
@@ -52,6 +53,8 @@ const MIME = {
52
53
 
53
54
  export function createWebServer(deps) {
54
55
  const { persona, log } = deps;
56
+ // DeviceManager(index.js 注入;独立运行/无宿主时可缺省,设备路由照常、运行态清理跳过)。
57
+ const devices = deps.devices;
55
58
  // 自定义 LLM provider 注册服务(index.js 注入;缺省时保存模型不注册,功能照旧)。
56
59
  const llmProviders = deps.llmProviders;
57
60
  const host = deps.web?.host ?? '127.0.0.1';
@@ -164,17 +167,19 @@ export function createWebServer(deps) {
164
167
  status: bot.status,
165
168
  };
166
169
  }
167
- async function publicRole(role) {
168
- // 先恢复 dsh 重启前的运行表,runningCount 才准确。
169
- await recoverLifeScripts(role.workspace);
170
- await pruneDeadLifeScripts(role.workspace);
170
+ async function publicRole(role) {
171
+ // 休眠角色不能在打开管理页时被运行表自动复活。
172
+ const bot = roleBot(role.roleId);
173
+ if (bot.enabled !== false) await recoverLifeScripts(role.workspace);
174
+ await pruneDeadLifeScripts(role.workspace);
171
175
  return {
172
176
  roleId: role.roleId,
173
177
  persona: role.persona,
174
178
  model: role.model,
175
179
  proactive: role.proactive,
176
- binding: role.binding,
177
- bot: roleBot(role.roleId),
180
+ binding: role.binding,
181
+ voice: publicVoiceConfig(role.voice),
182
+ bot,
178
183
  life: {
179
184
  hasScript: (await listLifeScripts(role.workspace)).length > 0,
180
185
  runningCount: listRunningLifeScripts(role.workspace).length,
@@ -192,6 +197,18 @@ export function createWebServer(deps) {
192
197
  const backups = await readdir(join(lifeDir, '.backup')).then((a) => a.sort().reverse()).catch(() => []);
193
198
  return { manifest, logs: logs.slice(0, 50), backups: backups.slice(0, 50), running: listRunningLifeScripts(role.workspace) };
194
199
  }
200
+ /** 玩具操控脚本监管:脚本清单 + .logs + 运行中(与 life 同级,完全透明)。 */
201
+ async function toysStatus(roleId) {
202
+ const role = await persona.loadRole(roleId);
203
+ if (!role) return null;
204
+ const toysDir = join(role.workspace, 'toys');
205
+ const scripts = await readdir(toysDir).then((a) => a.filter((n) => /\.(mjs|js|ts)$/.test(n)).sort()).catch(() => []);
206
+ const logs = await readdir(join(toysDir, '.logs')).then((a) => a.sort().reverse()).catch(() => []);
207
+ const running = (typeof devices?.listScriptRuns === 'function' ? devices.listScriptRuns() : [])
208
+ .filter((r) => r.roleId === roleId)
209
+ .map((r) => ({ runId: r.runId, scriptName: r.scriptName, pid: r.pid, startedAt: r.startedAt }));
210
+ return { scripts, logs: logs.slice(0, 50), running };
211
+ }
195
212
  /** 安全化角色 id 参数(防路径穿越)。 */
196
213
  function roleParam(raw) {
197
214
  const rid = String(raw ?? '');
@@ -230,9 +247,21 @@ export function createWebServer(deps) {
230
247
  speakingStyle: String(p.speakingStyle ?? '').trim() || undefined,
231
248
  relationship: String(p.relationship ?? '').trim() || undefined,
232
249
  schedule,
250
+ devices: (p.devices !== undefined && Array.isArray(p.devices))
251
+ ? [...new Set(p.devices.map((d) => String(d)).filter((d) => /^[A-Za-z0-9._-]+$/.test(d)))]
252
+ : undefined,
233
253
  };
234
254
  }
235
255
 
256
+ /** 校验 persona.devices 每项都是 me 名下的设备;返回非法 deviceId 或 null。 */
257
+ async function checkDevicesOwned(p, me) {
258
+ for (const id of Array.isArray(p?.devices) ? p.devices : []) {
259
+ const dev = await persona.loadDevice(id).catch(() => null);
260
+ if (!dev || dev.owner !== me.qqNumber) return id;
261
+ }
262
+ return null;
263
+ }
264
+
236
265
  /**
237
266
  * 应用 model/proactive patch 并同步自定义 provider(POST 新建与 PUT 编辑共用)。
238
267
  * model 保存时去掉空值键(清空的字段等同不配置);provider 留空由 providerRoute
@@ -357,6 +386,8 @@ export function createWebServer(deps) {
357
386
  const b = await readBody(req);
358
387
  const personaFields = normalizePersona(b);
359
388
  if (!personaFields.name) { sendJson(res, 400, { ok: false, error: '请填写角色名' }); return; }
389
+ const bad = await checkDevicesOwned(personaFields, me);
390
+ if (bad) { sendJson(res, 400, { ok: false, error: `设备 ${bad} 不归你所有` }); return; }
360
391
  const roleId = await persona.createRole({ accountId: me.qqNumber, persona: personaFields });
361
392
  // 首次保存同样落 model/proactive(修:新建角色一次保存即生效,而非只有再编辑才存)。
362
393
  const role = await applyModelProactive(roleId, b ?? {});
@@ -364,6 +395,41 @@ export function createWebServer(deps) {
364
395
  return;
365
396
  }
366
397
 
398
+ // ---- 我的设备库(用户级,角色经 persona.devices 勾选)----
399
+ if (pathname === '/api/me/devices' && req.method === 'GET') {
400
+ const list = await persona.listDevices(me.qqNumber);
401
+ sendJson(res, 200, { ok: true, devices: list });
402
+ return;
403
+ }
404
+ if (pathname === '/api/me/devices' && req.method === 'POST') {
405
+ const b = await readBody(req);
406
+ const alias = String(b?.alias ?? '').trim();
407
+ if (!alias) { sendJson(res, 400, { ok: false, error: '请填写设备别名' }); return; }
408
+ const kind = b?.kind === 'monsterparty' ? 'monsterparty' : 'monsterparty';
409
+ const device = await persona.createDevice({ owner: me.qqNumber, alias, kind });
410
+ sendJson(res, 200, { ok: true, device });
411
+ return;
412
+ }
413
+ const pDev = /^\/api\/me\/devices\/([^/]+)$/.exec(pathname);
414
+ if (pDev && req.method === 'DELETE') {
415
+ const did = /^[A-Za-z0-9._-]+$/.test(pDev[1]) ? pDev[1] : null;
416
+ if (!did) { sendJson(res, 400, { ok: false, error: '设备 ID 非法' }); return; }
417
+ const dev = await persona.loadDevice(did);
418
+ if (!dev || dev.owner !== me.qqNumber) { sendJson(res, 404, { ok: false, error: '设备不存在' }); return; }
419
+ const { removed, roleIds } = await persona.deleteDevice(did);
420
+ if (removed) {
421
+ for (const rid of roleIds) {
422
+ try { await devices?.disposeRole?.(rid); } catch { /* ignore */ }
423
+ try {
424
+ const r = await persona.loadRole(rid);
425
+ if (r) await persona.syncRoleMemory(r);
426
+ } catch { /* ignore */ }
427
+ }
428
+ }
429
+ sendJson(res, 200, { ok: true, removed });
430
+ return;
431
+ }
432
+
367
433
  const pm = /^\/api\/me\/roles\/([^/]+)$/.exec(pathname);
368
434
  if (pm) {
369
435
  const rid = roleParam(pm[1]);
@@ -376,6 +442,8 @@ export function createWebServer(deps) {
376
442
  const patch = b ?? {};
377
443
  if (patch.persona !== undefined) {
378
444
  const p = normalizePersona({ persona: patch.persona });
445
+ const bad = await checkDevicesOwned(p, me);
446
+ if (bad) { sendJson(res, 400, { ok: false, error: `设备 ${bad} 不归你所有` }); return; }
379
447
  p.owner = me.qqNumber;
380
448
  await persona.saveRoleField(rid, 'persona', p);
381
449
  }
@@ -388,6 +456,7 @@ export function createWebServer(deps) {
388
456
  try { await llmProviders.unregister(role); } catch (e) { log?.warn?.('pygmalion: 注销自定义 provider %s 失败 %o', rid, e); }
389
457
  }
390
458
  await botApi.removeForRole(rid);
459
+ try { await devices?.disposeRole?.(rid); } catch { /* ignore */ }
391
460
  await persona.deleteRole(rid);
392
461
  sendJson(res, 200, { ok: true, deleted: rid });
393
462
  return;
@@ -396,18 +465,53 @@ export function createWebServer(deps) {
396
465
  return;
397
466
  }
398
467
 
399
- // 我的角色的 QQ 机器人(凭据仅角色 owner 可配;qqSecret 不回传,空留=保持原值)。
468
+ // 我的角色的 QQ 机器人(凭据仅角色 owner 可配;qqSecret 不回传,空留=保持原值)。
469
+ const pVoiceReference = /^\/api\/me\/roles\/([^/]+)\/voice\/reference$/.exec(pathname);
470
+ if (pVoiceReference && req.method === 'POST') {
471
+ const rid = roleParam(pVoiceReference[1]);
472
+ const role = rid && await persona.loadRole(rid);
473
+ if (!role || !ownedBy(role, me.qqNumber)) { sendJson(res, 404, { ok: false, error: '角色不存在' }); return; }
474
+ try {
475
+ const b = await readBody(req);
476
+ sendJson(res, 200, { ok: true, voice: await saveReferenceAudio(rid, b ?? {}) });
477
+ } catch (e) { sendJson(res, 400, { ok: false, error: String(e?.message ?? e) }); }
478
+ return;
479
+ }
480
+ const pVoice = /^\/api\/me\/roles\/([^/]+)\/voice$/.exec(pathname);
481
+ if (pVoice) {
482
+ const rid = roleParam(pVoice[1]);
483
+ const role = rid && await persona.loadRole(rid);
484
+ if (!role || !ownedBy(role, me.qqNumber)) { sendJson(res, 404, { ok: false, error: '角色不存在' }); return; }
485
+ if (req.method === 'GET') { sendJson(res, 200, { ok: true, voice: publicVoiceConfig(await loadVoiceConfig(rid)) }); return; }
486
+ if (req.method === 'PUT') {
487
+ try { sendJson(res, 200, { ok: true, voice: await saveVoiceConfig(rid, await readBody(req)) }); }
488
+ catch (e) { sendJson(res, 400, { ok: false, error: String(e?.message ?? e) }); }
489
+ return;
490
+ }
491
+ sendJson(res, 405, { ok: false, error: 'method not allowed' }); return;
492
+ }
493
+
494
+ // 我的角色的 QQ 机器人(凭据仅角色 owner 可配;qqSecret 不回传,空留=保持原值)。
400
495
  const pBot = /^\/api\/me\/roles\/([^/]+)\/bot$/.exec(pathname);
401
496
  if (pBot) {
402
497
  const rid = roleParam(pBot[1]);
403
498
  if (!rid) { sendJson(res, 400, { ok: false, error: '角色 ID 非法' }); return; }
404
499
  const role = await persona.loadRole(rid);
405
500
  if (!role || !ownedBy(role, me.qqNumber)) { sendJson(res, 404, { ok: false, error: '角色不存在' }); return; }
406
- if (req.method === 'PUT') {
407
- const b = await readBody(req);
408
- try {
409
- await botApi.upsertForRole(rid, { ...(b ?? {}), owner: me.qqNumber });
410
- sendJson(res, 200, { ok: true, bot: roleBot(rid) });
501
+ if (req.method === 'PUT') {
502
+ const b = await readBody(req);
503
+ try {
504
+ await botApi.upsertForRole(rid, { ...(b ?? {}), owner: me.qqNumber });
505
+ // 休眠不仅断开 QQ 网关,也须停止角色已在运行的主动脚本和设备脚本。
506
+ if (b?.enabled === false) {
507
+ await stopLifeScripts(role.workspace);
508
+ try {
509
+ const toyRuns = devices?.listScriptRuns?.() ?? [];
510
+ await Promise.all(toyRuns.filter((run) => run.roleId === rid).map((run) => devices.stopScript(run.runId)));
511
+ await devices?.disposeRole?.(rid);
512
+ } catch { /* 设备清理失败不影响休眠 */ }
513
+ }
514
+ sendJson(res, 200, { ok: true, bot: roleBot(rid) });
411
515
  } catch (e) {
412
516
  sendJson(res, 400, { ok: false, error: String(e?.message ?? e) });
413
517
  }
@@ -548,6 +652,49 @@ export function createWebServer(deps) {
548
652
  return;
549
653
  }
550
654
 
655
+ // 玩具操控脚本监管(与生活脚本同级的透明监控)
656
+ const pToysStop = /^\/api\/me\/roles\/([^/]+)\/toys\/stop$/.exec(pathname);
657
+ if (pToysStop && req.method === 'POST') {
658
+ const rid = roleParam(pToysStop[1]);
659
+ if (!rid) { sendJson(res, 400, { ok: false, error: '角色 ID 非法' }); return; }
660
+ const role = await persona.loadRole(rid);
661
+ if (!role || !ownedBy(role, me.qqNumber)) { sendJson(res, 404, { ok: false, error: '角色不存在' }); return; }
662
+ if (!devices || typeof devices.stopScript !== 'function') { sendJson(res, 503, { ok: false, error: '设备服务不可用' }); return; }
663
+ const b = await readBody(req);
664
+ const runId = String(b?.runId ?? '').trim();
665
+ if (!runId) { sendJson(res, 400, { ok: false, error: '缺少 runId' }); return; }
666
+ const r = await devices.stopScript(runId);
667
+ sendJson(res, 200, r);
668
+ return;
669
+ }
670
+ const pToys = /^\/api\/me\/roles\/([^/]+)\/toys(?:\/(script|log)\/([^/]+))?$/.exec(pathname);
671
+ if (pToys && req.method === 'GET') {
672
+ const rid = roleParam(pToys[1]);
673
+ if (!rid) { sendJson(res, 400, { ok: false, error: '角色 ID 非法' }); return; }
674
+ const role = await persona.loadRole(rid);
675
+ if (!role || !ownedBy(role, me.qqNumber)) { sendJson(res, 404, { ok: false, error: '角色不存在' }); return; }
676
+ if (pToys[2]) {
677
+ let rawName = '';
678
+ try { rawName = decodeURIComponent(pToys[3]); } catch { /* 非法 % 序列 */ }
679
+ const name = pToys[2] === 'log' ? logFileNameParam(rawName) : scriptFileNameParam(rawName);
680
+ if (!name) { sendJson(res, 400, { ok: false, error: pToys[2] === 'log' ? '日志名非法' : '脚本名非法' }); return; }
681
+ const file = pToys[2] === 'log'
682
+ ? join(role.workspace, 'toys', '.logs', name)
683
+ : join(role.workspace, 'toys', name);
684
+ const base = pToys[2] === 'log'
685
+ ? join(role.workspace, 'toys', '.logs')
686
+ : join(role.workspace, 'toys');
687
+ if (!file.startsWith(base)) { sendJson(res, 400, { ok: false, error: '路径非法' }); return; }
688
+ const text = await readFile(file, 'utf8').catch(() => null);
689
+ if (text === null) { sendJson(res, 404, { ok: false, error: pToys[2] === 'log' ? '日志不存在' : '脚本不存在' }); return; }
690
+ res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' });
691
+ res.end(text);
692
+ return;
693
+ }
694
+ sendJson(res, 200, { ok: true, ...(await toysStatus(rid)) });
695
+ return;
696
+ }
697
+
551
698
  sendJson(res, 404, { ok: false, error: `not found: ${pathname}` });
552
699
  } catch (e) {
553
700
  log?.error?.('web-server error: %o', e);
@@ -0,0 +1,42 @@
1
+ // toy 脚本示例 —— 角色操控玩具设备的参考模板(dsh 自由改编)。
2
+ //
3
+ // 脚本只需关心两个参数,不接触任何驱动/通信细节:
4
+ // await toy.set({ intensity, stroke }) 改变强度 / 行程范围
5
+ // await toy.sleep(ms) 控制节奏
6
+ // toy.stop() 停止
7
+ // await toy.wake({ mood, topic, reason }) 合适时机请导演开口(如调情/回应)——可说可静默
8
+ //
9
+ // 参数语义(雷电):intensity 0-100(70~100 是 ta 常用的强区间);stroke 是一对行程边界
10
+ // "A,B",取值 0/33/66/100(0=L1 最深、100=L3 几乎拔出)。体感:0,100 大开大合、
11
+ // 0,66 幅度适宜有包裹感、0,33 快而轻、66,100 顶端附近。
12
+ //
13
+ // 脚本自然结束即终止,并保持最后一步的参数继续运行(不中断体验),系统会提醒导演可续可停;
14
+ // 若脚本想主动停设备,就在结束前调 toy.stop()。也可被 toy_run_script stop / toy_control stop 中途接管。
15
+ // 把本文件另存为 workspace/toys/ 下的新文件(勿覆盖已存在的),再用 toy_run_script 运行。
16
+
17
+ // 下面只是一个展示语法的简单例子——脚本的运作方式远不止这一种(可循环、可随 ta 的反应与对话气氛应变等),由你自由设计。
18
+ // 这段示范"渐进加深→起伏→收尾",雷电常用强度偏高,取 60~90。
19
+ const STEPS = [
20
+ { intensity: 60, stroke: '0,66', ms: 1800 }, // 舒适区、有包裹感
21
+ { intensity: 75, stroke: '0,66', ms: 2000 }, // 加强
22
+ { intensity: 90, stroke: '0,100', ms: 2400 }, // 大开大合
23
+ { wake: { mood: '俏皮', topic: '刚来了一段猛的', reason: '适合说一句撩人的话' } }, // 请导演开口
24
+ // 起伏:固定行程内反复调强度
25
+ { intensity: 70, stroke: '33,100', ms: 1100 },
26
+ { intensity: 90, stroke: '33,100', ms: 1100 },
27
+ { intensity: 70, stroke: '33,100', ms: 1100 },
28
+ { intensity: 95, stroke: '0,100', ms: 1500 },
29
+ // 收尾
30
+ { intensity: 80, stroke: '0,66', ms: 1300 },
31
+ { intensity: 65, stroke: '0,33', ms: 1200 },
32
+ // 脚本在此自然结束:设备保持上面这步的参数继续运行(体验不中断),系统会提醒导演可续可停;
33
+ // 若想让脚本主动停设备,把上面换成 { intensity: 0, ms: 500 } 或结束前 await toy.stop()
34
+ ];
35
+
36
+ for (const step of STEPS) {
37
+ if (step.wake) { await toy.wake(step.wake); continue; } // 合适时机请导演开口(可说可静默)
38
+ const p = { intensity: step.intensity };
39
+ if (step.stroke) p.stroke = step.stroke;
40
+ await toy.set(p); // toy.set 是异步的(内部经 HTTP 下发),务必 await
41
+ if (step.ms) await toy.sleep(step.ms);
42
+ }