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
@@ -1,581 +1,91 @@
1
- /**
2
- * DeviceManager —— 设备远控核心。进程内持有每个角色(roleId)的设备运行时:
3
- * - activation(token/session,仅内存,单次有效)来自 QQ 转发的分享链接;
4
- * - conn(MonsterPartyConn)懒建:首次 apply 才连 WS;
5
- * - 工具模式:applyFromTool 设置参数 + 可选时长,到点保持参数并提醒 dsh;
6
- * - 脚本模式:runToyScript 起 node 子进程注入全局 toy.set/stop,参数经 HTTP /toycmd 回来;
7
- * - 提醒 dsh 走 registerRole 注入的 wake 闭包(由 bot-factory 提供,force 唤醒,导演内部信号)。
8
- */
9
- import { spawn } from 'node:child_process';
10
- import { mkdirSync, writeFileSync, openSync, closeSync, existsSync } from 'node:fs';
11
- import { mkdir } from 'node:fs/promises';
12
- import { join, basename, extname, resolve, sep } from 'node:path';
13
- import { pathToFileURL } from 'node:url';
14
- import { parseLink as parseMp, resolveSession as resolveMp, MonsterPartyConn, MONSTERPARTY_CAPABILITY } from './monsterparty.mjs';
1
+ /** 内置驱动接线与旧 toy_* 入口兼容;通用执行层不认识具体型号。 */
2
+ import { fileURLToPath } from 'node:url';
3
+ import { createDeviceExtensionRegistry } from './registry.mjs';
4
+ import { createDeviceService } from './service.mjs';
5
+ import { createMonsterPartyController } from './monsterparty-controller.mjs';
6
+ import { monsterpartyDocMarkdown } from './monsterparty-doc.mjs';
7
+ export { normalizeStroke, TOY_REFERENCE_NAME } from './monsterparty-controller.mjs';
15
8
 
16
- const DEFAULT_BASE = 'http://127.0.0.1:3080';
17
- const REMIND_COALESCE_MS = 10_000; // 同类提醒 10s 合并,防堆积
18
- export const TOY_REFERENCE_NAME = '玩具脚本示例.mjs';
19
-
20
- /** 角色工作区中的可读参考。它只示范“连续波形 + 脚本内唤醒”的接口位置;具体波形由导演自行创作。 */
21
- const TOY_REFERENCE_SOURCE = `// 玩具脚本参考:先理解接口和 wake 的位置,再自行创作实际波形。
22
- const clamp = (value, low, high) => Math.max(low, Math.min(high, value));
23
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
24
-
25
- const startedAt = Date.now();
26
- const durationMs = 90_000;
27
- let woke = false;
28
-
29
- while (Date.now() - startedAt < durationMs) {
30
- const seconds = (Date.now() - startedAt) / 1000;
31
- const intensity = Math.round(clamp(65 + 20 * Math.sin(seconds * 0.7), 0, 100));
32
- const stroke = Math.sin(seconds * 0.7) >= 0 ? '0,66' : '0,100';
33
- await toy.set({ intensity, stroke });
34
-
35
- if (!woke && seconds >= 35) {
36
- woke = true;
37
- await toy.wake({ reason: '脚本中的玩具运动产生了值得导演感知的变化' });
38
- }
39
- await toy.sleep(700);
40
- }
41
- `;
42
-
43
- function ensureToyReference(workspace) {
44
- if (!workspace) return;
45
- try {
46
- const toysDir = join(workspace, 'toys');
47
- mkdirSync(toysDir, { recursive: true });
48
- const file = join(toysDir, TOY_REFERENCE_NAME);
49
- if (!existsSync(file)) writeFileSync(file, TOY_REFERENCE_SOURCE, 'utf8');
50
- } catch { /* 参考文件写入失败不阻塞设备激活或脚本运行 */ }
51
- }
52
-
53
- /** toy 脚本 helper:注入 globalThis.toy({ set/stop/sleep }),经 HTTP /toycmd 下发参数。 */
54
- const TOY_HELPER_SOURCE = `// auto-generated by pygmalion (device toy helper). do not edit.
55
- const __pgToyCmd = async (payload) => {
56
- const base = process.env.PYG_TOY_BASE || '${DEFAULT_BASE}';
57
- const path = process.env.PYG_HTTP_API_PATH || '';
58
- const token = process.env.PYG_TOKEN || '';
59
- const res = await fetch(base + path + '/toycmd', {
60
- method: 'POST',
61
- headers: { 'content-type': 'application/json', authorization: 'Bearer ' + token },
62
- body: JSON.stringify(payload),
63
- });
64
- const text = await res.text().catch(() => '');
65
- let j = null; try { j = JSON.parse(text); } catch { /* ignore */ }
66
- if (!res.ok || (j && j.ok === false)) throw new Error('toycmd ' + res.status + ' ' + ((j && j.error) || text).slice(0, 200));
67
- return j;
68
- };
69
- globalThis.toy = {
70
- async set(params) { return __pgToyCmd({ action: 'apply', ...(params || {}) }); },
71
- async stop() { return __pgToyCmd({ action: 'stop' }); },
72
- async sleep(ms) { await new Promise((r) => setTimeout(r, Math.max(0, Number(ms) || 0))); },
73
- async wake(w) { return __pgToyCmd({ action: 'wake', ...(w || {}) }); },
74
- };
75
- `;
76
-
77
- /** 驱动注册表(v1 仅 monsterparty)。kind → { capability, parseLink, resolveSession, Conn } */
78
- const DRIVERS = {
79
- monsterparty: {
80
- capability: MONSTERPARTY_CAPABILITY,
81
- parseLink: parseMp,
82
- resolveSession: resolveMp,
83
- Conn: MonsterPartyConn,
84
- },
85
- };
86
-
87
- /** 行程参数归一:接受 "0,66" / "33,100" / "L1,L2" / "L1 L2" / "L2"(区间) 等。返回 [a,b] 或 null。 */
88
- export function normalizeStroke(value, cap) {
89
- const zones = cap?.stroke?.zones;
90
- const tok = (s) => {
91
- const t = String(s ?? '').trim().toUpperCase();
92
- if (zones && zones[t]) return zones[t]; // L1/L2/L3 区间
93
- const n = Number(t);
94
- return Number.isFinite(n) ? [n, n] : null;
95
- };
96
- const raw = String(value ?? '').trim();
97
- if (!raw) return null;
98
- const parts = raw.split(/[,,\s~至\-]+/).filter(Boolean).map(tok);
99
- if (!parts.length || parts.some((p) => !p)) return null;
100
- const a = Math.min(...parts.map((p) => p[0]));
101
- const b = Math.max(...parts.map((p) => p[1]));
102
- if (!Number.isFinite(a) || !Number.isFinite(b) || a < 0 || b > 100 || a > b) return null;
103
- return [a, b];
104
- }
105
-
106
- /**
107
- * 建 DeviceManager。
108
- * @param {object} deps { persona, log?, baseUrl? }(getWake 可选由 registerRole 提供)
109
- */
110
9
  export function createDeviceManager(deps) {
111
- const persona = deps.persona;
112
- const log = deps.log;
113
- const baseUrl = deps.baseUrl || DEFAULT_BASE;
114
- const drivers = deps.drivers || DRIVERS;
115
-
116
- /** roleId → { deviceId, alias, token, session }(内存激活态,token 不落盘) */
117
- const activations = new Map();
118
- /** roleId → DeviceRuntime */
119
- const runtimes = new Map();
120
- /** roleId → wake 闭包(bot-factory 注入):async (contextText, { priority }) => wakeupSession(...) */
121
- const wakes = new Map();
122
- /** runId → script run */
123
- const scriptRuns = new Map();
124
- let toySeq = 0;
125
-
126
- /** 把某工作区当前运行的 toy 脚本落盘 toys/.running.json(监管/重启后可见)。 */
127
- function persistToysRunning(workspace) {
128
- const ws = String(workspace ?? '');
129
- if (!ws) return;
130
- const list = [...scriptRuns.values()]
131
- .filter((r) => r.workspace === ws)
132
- .map((r) => ({ runId: r.runId, script: basename(r.script), pid: r.pid, startedAt: r.startedAt }));
133
- try {
134
- mkdirSync(join(ws, 'toys'), { recursive: true });
135
- writeFileSync(join(ws, 'toys', '.running.json'), JSON.stringify(list, null, 2), 'utf8');
136
- } catch { /* 落盘失败不阻塞 */ }
137
- }
138
-
139
- function info(...args) { log?.info?.(...args); }
140
- function warn(...args) { log?.warn?.(...args); }
141
-
142
- async function roleOf(roleId) {
143
- return persona?.loadRole ? await persona.loadRole(roleId).catch(() => null) : null;
144
- }
145
-
146
- /** 该角色授权的 monsterparty 设备(未指定 deviceId 且有多个 → 需指定)。 */
147
- async function authorizedDevice(role, kind, deviceId) {
148
- if (!role?.persona) return null;
149
- const owner = role.persona.owner;
150
- const ids = Array.isArray(role.persona.devices) ? role.persona.devices : [];
151
- const wanted = deviceId || (ids.length === 1 ? ids[0] : null);
152
- if (!wanted || !ids.includes(wanted)) return null;
153
- const dev = await persona.loadDevice?.(wanted).catch(() => null);
154
- return dev && dev.owner === owner ? dev : null;
155
- }
156
-
157
- // ---------------- 状态机 ----------------
158
- function runtime(roleId) {
159
- let rt = runtimes.get(roleId);
160
- if (!rt) {
161
- rt = {
162
- roleId,
163
- deviceId: null,
164
- activation: null,
165
- conn: null,
166
- controller: 'idle', // idle | tool | script
167
- last: { intensity: 0, stroke: null },
168
- phaseTimer: null,
169
- phaseGeneration: 0,
170
- script: null,
171
- lastRemindAt: 0,
172
- };
173
- runtimes.set(roleId, rt);
174
- }
175
- return rt;
176
- }
177
-
178
- function clearPhase(rt) {
179
- rt.phaseGeneration++;
180
- if (rt.phaseTimer) { clearTimeout(rt.phaseTimer); rt.phaseTimer = null; }
181
- }
182
- function killScript(rt) {
183
- const ws = rt?.script?.workspace;
184
- if (rt.script?.child) {
185
- try { rt.script.child.kill('SIGTERM'); } catch { /* ignore */ }
186
- try { rt.script.child.kill('SIGKILL'); } catch { /* ignore */ }
187
- }
188
- if (rt.script?.runId) scriptRuns.delete(rt.script.runId);
189
- rt.script = null;
190
- if (ws) persistToysRunning(ws);
191
- }
192
- async function waitForChildExit(child, timeoutMs) {
193
- if (!child || child.exitCode !== null || child.signalCode != null) return true;
194
- return await new Promise((resolveDone) => {
195
- let settled = false;
196
- const done = (value) => {
197
- if (settled) return;
198
- settled = true;
199
- clearTimeout(timer);
200
- child.off('close', onClose);
201
- child.off('error', onError);
202
- resolveDone(value);
203
- };
204
- const onClose = () => done(true);
205
- const onError = () => done(true);
206
- const timer = setTimeout(() => done(false), timeoutMs);
207
- timer.unref?.();
208
- child.once('close', onClose);
209
- child.once('error', onError);
210
- if (child.exitCode !== null || child.signalCode != null) done(true);
211
- });
212
- }
213
- async function stopConn(rt) {
214
- const conn = rt.conn;
215
- if (conn) {
216
- try { conn.stop(); } catch { /* ignore */ }
217
- }
218
- }
219
- async function closeConn(rt) {
220
- if (rt.conn) { try { rt.conn.close(); } catch { /* ignore */ } rt.conn = null; }
221
- }
222
-
223
- /** 建立连接(懒建)。失败返回错误对象。 */
224
- async function ensureConn(rt) {
225
- if (rt.conn) return null;
226
- const act = rt.activation;
227
- if (!act) return { error: '设备未激活', code: 'not-activated' };
228
- const drv = drivers[act.kind];
229
- if (!drv) return { error: `未知设备类型 ${act.kind}`, code: 'no-driver' };
230
- const conn = new drv.Conn(act.session, { log });
231
- try {
232
- await conn.connect();
233
- } catch (e) {
234
- // 连接/加入失败(如 duplicate receiver / 链接已失效)→ 清 activation,要求重发链接
235
- warn('mp connect fail role=%s: %s', rt.roleId, e.message);
236
- activations.delete(rt.roleId);
237
- rt.activation = null;
238
- rt.deviceId = null;
239
- return { error: `设备连接失败: ${e.message}(分享链接可能已失效,请重新发一条)`, code: 'expired' };
240
- }
241
- rt.conn = conn;
242
- info('device conn ready role=%s device=%s', rt.roleId, act.alias);
243
- return null;
244
- }
245
-
246
- function rtState(rt) {
247
- return {
248
- deviceId: rt.deviceId,
249
- alias: rt.activation?.alias ?? null,
250
- activated: Boolean(rt.activation),
251
- controller: rt.controller,
252
- last: rt.last.intensity !== 0 || rt.last.stroke ? { ...rt.last } : null,
253
- runId: rt.script?.runId ?? null,
254
- };
255
- }
256
-
257
- /** 提醒 dsh(10s 合并同类)。contextText 已是 [设备事件] 文本。 */
258
- async function notify(rt, text, { priority = false } = {}) {
259
- const wake = wakes.get(rt.roleId);
260
- if (typeof wake !== 'function') return { ok: false, error: 'no-wake' };
261
- const now = Date.now();
262
- if (!priority && now - rt.lastRemindAt < REMIND_COALESCE_MS) return { ok: false, skipped: 'coalesced' };
263
- rt.lastRemindAt = now;
264
- try { await wake(text, { priority }); return { ok: true }; }
265
- catch (e) { warn('device notify role=%s fail: %s', rt.roleId, e?.message ?? e); return { ok: false, error: String(e) }; }
266
- }
267
-
268
- /** 结束一段(工具计时到点 / 脚本结束):保持当前参数,提醒 dsh。 */
269
- async function finishPhase(rt, { kind, detail, phaseGeneration }) {
270
- // 被后续脚本/工具清除的旧计时,即使回调已经进入任务队列也不能再唤醒导演。
271
- if (kind === 'tool' && phaseGeneration !== rt.phaseGeneration) return;
272
- rt.phaseTimer = null;
273
- rt.controller = 'idle'; // 设备仍在跑(conn 持续刷新),dsh 决定再调或停
274
- const lastText = rt.last.stroke
275
- ? `强度 ${rt.last.intensity}、行程 ${rt.last.stroke.join(',')}`
276
- : rt.last.intensity
277
- ? `强度 ${rt.last.intensity}`
278
- : '已停';
279
- const text = kind === 'script'
280
- ? `[设备事件] 你的操控脚本「${detail}」已结束,当前设备保持最后参数(${lastText})继续运行。若需要可再 toy_run_script 或 toy_control;要停用 toy_control 停。`
281
- : `[设备事件] 本次 toy_control 计时结束,设备保持当前参数(${lastText})继续运行。可再次调用 toy_control 调整或停止。`;
282
- await notify(rt, text, { priority: kind === 'script' });
283
- }
284
-
285
- // ---------------- 对外 API ----------------
286
- return {
287
- registerRole(roleId, wake) { if (roleId && typeof wake === 'function') wakes.set(roleId, wake); },
288
- unregisterRole(roleId) { wakes.delete(roleId); },
289
-
290
- /** 文本里找设备分享链接。@returns { token, raw, kind } | null */
291
- detectLink(text) {
292
- const s = String(text ?? '');
293
- for (const drv of Object.values(drivers)) {
294
- const hit = drv.parseLink(s);
295
- if (hit) return hit;
296
- }
297
- return null;
10
+ const extensions = deps.extensions ?? createDeviceExtensionRegistry();
11
+ const controllers = new Map(), wakes = new Map();
12
+ const controller = id => {
13
+ if (!controllers.has(id)) controllers.set(id, createMonsterPartyController(deps));
14
+ return controllers.get(id);
15
+ };
16
+ const control = { description: '设置雷电参数,省略的参数保持原值。',
17
+ parameters: { type: 'object', additionalProperties: false, properties: {
18
+ intensity: { type: 'number' }, stroke: { type: 'string' }, seconds: { type: 'number' } } },
19
+ async execute(instance, input, context) {
20
+ return instance.controller.applyFromTool({ ...input, roleId: context.roleId, deviceId: context.deviceId, fromScript: context.fromScript });
21
+ } };
22
+ const releaseBuiltin = extensions.registerDeviceDriver({ apiVersion: 1, id: 'monsterparty', name: 'MonsterParty 雷电',
23
+ skill: { name: 'pygmalion-toy-control', description: '使用 MonsterParty 分享链接激活雷电,控制参数、编写脚本并管理控制交接。',
24
+ path: fileURLToPath(new URL('../../skills/pygmalion-toy-control/SKILL.md', import.meta.url)) },
25
+ operations: { control, stop: { description: '停止雷电运动。', parameters: { type: 'object', properties: {}, additionalProperties: false },
26
+ execute: (instance, _input, context) => instance.controller.applyFromTool({ roleId: context.roleId, deviceId: context.deviceId, stop: true, fromScript: context.fromScript }) } },
27
+ legacyTools: ['toy_status', 'toy_control', 'toy_run_script'],
28
+ matchInput: text => controller('link-parser').detectLink(text),
29
+ async acceptInput(instance, match, { openid }) {
30
+ await service.stopDeviceScripts(instance.deviceId, 'disposed');
31
+ return instance.controller.activate(instance.roleId, match.token, { openid, deviceId: instance.deviceId });
298
32
  },
299
-
300
- /**
301
- * QQ 转发链接激活。@returns { ok:true, deviceId, alias } | { ok:false, error, code }
302
- * code: no-device(未授权) / invalid(解析失败) / not-owner / ok
303
- */
304
- async activate(roleId, token, { openid } = {}) {
305
- const role = await roleOf(roleId);
306
- if (!role?.persona) return { ok: false, error: '角色不存在', code: 'no-role' };
307
- ensureToyReference(role.workspace);
308
- if (role.binding?.openid && openid && role.binding.openid !== openid)
309
- return { ok: false, error: '非设备拥有者', code: 'not-owner' };
310
- // 匹配该角色授权中的 monsterparty 设备(链接可能来自任一授权设备,单台场景直接命中)
311
- const dev = await authorizedDevice(role, 'monsterparty', null);
312
- if (!dev) return { ok: false, error: '该角色未配置可用设备(请在管理台「我的设备」登记并为角色勾选)', code: 'no-device' };
313
- const res = await drivers.monsterparty.resolveSession(token);
314
- if (!res.ok) return { ok: false, error: res.error, code: 'invalid' };
315
- // 若已激活/已连旧会话 → 断开旧 conn(等新 token 用于下次 apply)
316
- const old = runtimes.get(roleId);
317
- if (old) { clearPhase(old); killScript(old); await closeConn(old); }
318
- activations.set(roleId, { deviceId: dev.id, alias: dev.alias, kind: dev.kind, token, session: res.session });
319
- info('device activated role=%s device=%s', roleId, dev.alias);
320
- return { ok: true, deviceId: dev.id, alias: dev.alias };
33
+ async create({ roleId, deviceId }) {
34
+ const item = controller(deviceId); if (wakes.has(roleId)) item.registerRole(roleId, wakes.get(roleId));
35
+ return { controller: item, roleId, deviceId, workspace: (await deps.persona.loadRole(roleId)).workspace };
321
36
  },
322
-
323
- /** 当前角色授权设备 + 激活/运行状态(供 toy_status)。 */
324
- async status(roleId) {
325
- const role = await roleOf(roleId);
326
- if (!role?.persona) return { ok: false, error: '角色不存在' };
327
- const ids = Array.isArray(role.persona.devices) ? role.persona.devices : [];
328
- const out = [];
329
- for (const id of ids) {
330
- const dev = await persona.loadDevice?.(id).catch(() => null);
331
- if (!dev || dev.owner !== role.persona.owner) continue;
332
- const act = activations.get(roleId);
333
- const rt = runtimes.get(roleId);
334
- out.push({
335
- deviceId: id, alias: dev.alias, kind: dev.kind,
336
- activated: act?.deviceId === id,
337
- controller: rt?.controller ?? 'idle',
338
- last: rt && (rt.last.intensity !== 0 || rt.last.stroke) ? { ...rt.last } : null,
339
- runId: rt?.script?.runId ?? null,
340
- });
341
- }
342
- return { ok: true, devices: out };
37
+ dispose: instance => instance.controller.disposeRole(instance.roleId),
38
+ document: monsterpartyDocMarkdown,
39
+ async snapshot({ roleId, deviceId }) { return (await controllers.get(deviceId)?.status(roleId))?.devices.find(item => item.deviceId === deviceId) ?? { activated: false }; },
40
+ scriptAliases: [{ name: 'toy', methods: { set: 'control', stop: 'stop', sleep: '$sleep', wake: '$wake' } }],
41
+ scriptStart(instance, info) { instance.controller.beginScript({ ...info, workspace: instance.workspace }); },
42
+ scriptEnd(instance, info) { return instance.controller.endScript(info); },
43
+ });
44
+ const service = createDeviceService({ ...deps, extensions });
45
+ async function select(roleId, deviceId) {
46
+ const role = await deps.persona.loadRole(roleId);
47
+ if (!role) throw Object.assign(new Error('角色不存在'), { code: 'no-role' });
48
+ const candidates = [];
49
+ for (const id of role.persona.devices ?? []) {
50
+ const device = await deps.persona.loadDevice(id);
51
+ if (device?.owner === role.persona.owner && device.kind === 'monsterparty' && (!deviceId || id === deviceId)) candidates.push(device);
52
+ }
53
+ if (candidates.length !== 1) throw Object.assign(new Error('请指定一台已授权的雷电设备'), { code: 'no-device' });
54
+ return candidates[0];
55
+ }
56
+ const failed = error => ({ ok: false, code: error.code, error: error.code === 'script-active'
57
+ ? `${error.message};请使用 toy_run_script stop 终止脚本。` : error.message });
58
+ return { ...service,
59
+ async monsterpartyStatus(roleId) { const result = await service.status(roleId); return { ...result, devices: result.devices.filter(device => device.kind === 'monsterparty') }; },
60
+ registerRole(roleId, callback) { wakes.set(roleId, callback); service.registerRole(roleId, callback); for (const item of controllers.values()) item.registerRole(roleId, callback); },
61
+ unregisterRole(roleId) { wakes.delete(roleId); service.unregisterRole(roleId); for (const item of controllers.values()) item.unregisterRole(roleId); },
62
+ detectLink: text => controller('link-parser').detectLink(text),
63
+ async activate(roleId, token, options = {}) {
64
+ try {
65
+ const device = await select(roleId, options.deviceId);
66
+ await service.stopDeviceScripts(device.id, 'disposed');
67
+ const item = controller(device.id); if (wakes.has(roleId)) item.registerRole(roleId, wakes.get(roleId));
68
+ return item.activate(roleId, token, { ...options, deviceId: device.id });
69
+ } catch (error) { return failed(error); }
343
70
  },
344
-
345
- /**
346
- * 统一参数入口。params: { roleId, deviceId?, intensity?, stroke?, seconds?, stop?, fromScript? }。
347
- * fromScript=true 表示调用来自运行中的 toy 脚本自身(经 /toycmd):不得杀自己/设计时,只落参数。
348
- * seconds>0:定时,到点保持参数并提醒;stop:停(清计时/脚本,强度归零)。
349
- */
350
71
  async applyFromTool(params) {
351
- const { roleId, fromScript } = params;
352
- if (!roleId) return { ok: false, error: '缺少 roleId' };
353
- const role = await roleOf(roleId);
354
- if (!role?.persona) return { ok: false, error: '角色不存在', code: 'no-role' };
355
- const dev = await authorizedDevice(role, 'monsterparty', params.deviceId);
356
- if (!dev) return { ok: false, error: '该角色未配置可用设备', code: 'no-device' };
357
- const rt = runtime(roleId);
358
-
359
- // stop:停当前(脚本自身 stop 不杀自己,只停设备;dsh 工具 stop 清计时+杀脚本)
360
- if (params.stop === true) {
361
- const stoppedScript = !fromScript ? rt.script : null;
362
- if (!fromScript) { clearPhase(rt); killScript(rt); }
363
- await stopConn(rt);
364
- rt.last = { intensity: 0, stroke: null };
365
- if (!fromScript) rt.controller = 'idle';
366
- if (stoppedScript) {
367
- await notify(rt, `[设备事件] 玩具操控脚本「${basename(stoppedScript.script)}」已被 toy_control stop 终止,设备也已停止。`,
368
- { priority: true });
369
- }
370
- return { ok: true, state: rtState(rt) };
371
- }
372
-
373
- // 玩具脚本拥有排他的控制权。普通工具调用不得暗中杀掉脚本;导演必须先显式终止脚本。
374
- if (!fromScript && rt.script) {
375
- return { ok: false, code: 'script-active',
376
- error: `玩具脚本「${basename(rt.script.script)}」正在运行(runId=${rt.script.runId});请先用 toy_run_script stop=${rt.script.runId} 终止脚本,再调用 toy_control。` };
377
- }
378
-
379
- // 激活检查:必须是这台授权设备
380
- const act = activations.get(roleId);
381
- if (!act || act.deviceId !== dev.id) {
382
- return {
383
- ok: false, code: 'not-activated', error: `设备「${dev.alias}」尚未激活——请让 ta 在 QQ 发一条新鲜的 MonsterParty 分享链接。`,
384
- };
385
- }
386
- rt.activation = act;
387
- rt.deviceId = dev.id;
388
-
389
- // 普通工具的新计时可替换旧计时;脚本自身调用始终保持 script 控制者。
390
- if (!fromScript && rt.phaseTimer) clearPhase(rt);
391
- const err = await ensureConn(rt);
392
- if (err) { rt.activation = null; activations.delete(roleId); return { ok: false, ...err }; }
393
-
394
- const cap = drivers.monsterparty.capability;
395
- // 参数归一
396
- if (params.intensity !== undefined) {
397
- const v = Math.max(cap.intensity.min, Math.min(cap.intensity.max, Math.round(Number(params.intensity))));
398
- if (!Number.isFinite(v)) return { ok: false, error: '强度须为数字', code: 'bad-params' };
399
- rt.last.intensity = v;
400
- }
401
- if (params.stroke !== undefined) {
402
- const ab = normalizeStroke(params.stroke, cap);
403
- if (!ab) return { ok: false, error: `行程格式无效(如 "0,66"/"L1 L2"/"0,0"): ${params.stroke}`, code: 'bad-params' };
404
- rt.last.stroke = ab;
405
- }
406
- // 落设备:行程变更发 segment;强度>0 持续 slider;强度=0 停止
407
- if (rt.last.stroke) rt.conn.sendStroke(rt.last.stroke[0], rt.last.stroke[1]);
408
- rt.conn.setIntensity(rt.last.intensity);
409
-
410
- // 脚本自身调用只落参数(节奏由脚本 toy.sleep 控制),dsh 定时模式才设计时
411
- if (fromScript) return { ok: true, state: rtState(rt) };
412
- if (Number(params.seconds) > 0) {
413
- clearPhase(rt);
414
- const ms = Math.round(Number(params.seconds) * 1000);
415
- rt.controller = 'tool';
416
- const phaseGeneration = rt.phaseGeneration;
417
- rt.phaseTimer = setTimeout(() => { void finishPhase(rt, { kind: 'tool', phaseGeneration }); }, ms);
418
- rt.phaseTimer.unref?.();
419
- } else {
420
- rt.controller = 'tool';
421
- }
422
- return { ok: true, state: rtState(rt) };
423
- },
424
-
425
- /** 启动 toy 脚本(dsh 在 workspace/toys/ 写的 .mjs/.js/.ts)。 */
426
- async runScript({ roleId, scriptPath, workspace, httpApiToken, httpApiPath, openid, reason }) {
427
- const role = await roleOf(roleId);
428
- if (!role?.persona) return { ok: false, error: '角色不存在' };
429
- // 校验脚本位于 workspace/toys/ 内且存在
430
- const toysDir = join(workspace, 'toys');
431
- ensureToyReference(workspace);
432
- const full = resolve(scriptPath);
433
- const toysRoot = resolve(toysDir) + sep;
434
- if (!full.startsWith(toysRoot)) return { ok: false, error: '脚本必须在 workspace/toys/ 目录内' };
435
- const ext = extname(full).toLowerCase();
436
- if (!['.mjs', '.js', '.ts'].includes(ext)) return { ok: false, error: 'toy 脚本仅支持 .mjs/.js/.ts(node)' };
437
- if (!existsSync(full)) return { ok: false, error: `toys/${basename(full)} 不存在` };
438
-
439
- const rt = runtime(roleId);
440
- if (rt.script || rt.phaseTimer) { clearPhase(rt); killScript(rt); }
441
-
442
- // helper 写入 toys/ 目录
443
- try { mkdirSync(toysDir, { recursive: true }); } catch { /* ignore */ }
444
- const helperPath = join(toysDir, '.toy-helper.mjs');
445
- try { writeFileSync(helperPath, TOY_HELPER_SOURCE, 'utf8'); } catch { return { ok: false, error: 'helper 写入失败' }; }
446
-
447
- const startedAt = Date.now();
448
- const runId = `toy-${Date.now().toString(36)}-${(toySeq++).toString(36)}`;
449
-
450
- // 日志文件
451
- let fd = null;
452
72
  try {
453
- await mkdir(join(toysDir, '.logs'), { recursive: true });
454
- fd = openSync(join(toysDir, '.logs', `${basename(full).replace(/\.[^.]+$/, '')}-${startedAt}.log`), 'a');
455
- } catch { fd = null; }
456
- const env = {
457
- ...process.env,
458
- PYG_TOY_BASE: baseUrl,
459
- PYG_HTTP_API_PATH: httpApiPath || '',
460
- PYG_TOKEN: httpApiToken || '',
461
- PYG_QQ: String(roleId ?? ''),
462
- PYG_OPENID: String(openid ?? ''),
463
- PYG_WORKSPACE: String(workspace ?? ''),
464
- };
465
- const args = ['--import', pathToFileURL(helperPath).href, full];
466
- let child;
467
- try {
468
- child = spawn(process.execPath, args, {
469
- env,
470
- stdio: fd != null ? ['ignore', fd, fd] : ['ignore', 'pipe', 'pipe'],
471
- windowsHide: true,
472
- });
473
- } catch (e) {
474
- if (fd != null) { try { closeSync(fd); } catch { /* ignore */ } }
475
- return { ok: false, error: `spawn 失败: ${String(e)}` };
476
- }
477
- const run = { runId, roleId, workspace, script: full, pid: child.pid, startedAt, child };
478
- scriptRuns.set(runId, run);
479
- rt.script = run;
480
- rt.controller = 'script';
481
- persistToysRunning(workspace);
482
-
483
- child.on('error', (e) => {
484
- warn('toy script error %s: %s', runId, e.message);
485
- const stillCurrent = rt.script?.runId === runId;
486
- if (rt.script?.runId === runId) { rt.script = null; rt.controller = 'idle'; }
487
- scriptRuns.delete(runId);
488
- persistToysRunning(workspace);
489
- if (fd != null) { try { closeSync(fd); } catch { /* ignore */ } }
490
- if (stillCurrent) void notify(rt, `[脚本结束] 玩具脚本「${basename(full)}」启动失败:${e.message}\n日志目录:toys/.logs/`, { priority: true });
491
- });
492
- child.on('close', (code) => {
493
- if (fd != null) { try { closeSync(fd); } catch { /* ignore */ } }
494
- const stillCurrent = rt.script?.runId === runId;
495
- if (rt.script?.runId === runId) { rt.script = null; rt.controller = 'idle'; }
496
- scriptRuns.delete(runId);
497
- persistToysRunning(workspace);
498
- if (stillCurrent && run.stopping !== true) {
499
- const label = basename(full);
500
- void finishPhase(rt, { kind: 'script', detail: label, exitCode: code });
501
- }
502
- });
503
- return { ok: true, runId, pid: child.pid, startedAt, script: full, reason };
73
+ const device = await select(params.roleId, params.deviceId);
74
+ // HTTP 兼容入口不能冒充由通用运行器签发的脚本租用。
75
+ const stopped = params.stop && !params.fromScript ? service.listScriptRuns().filter(run => run.deviceId === device.id && run.roleId === params.roleId) : [];
76
+ for (const run of stopped) await service.stopScript(run.runId, params.roleId, 'control-stop');
77
+ const input = Object.fromEntries(['intensity', 'stroke', 'seconds'].filter(key => params[key] !== undefined).map(key => [key, params[key]]));
78
+ const result = await service.invoke(params.roleId, device.id, params.stop ? 'stop' : 'control', params.stop ? {} : input);
79
+ if (result.ok) for (const run of stopped) await controller(device.id).controlStoppedScript({ roleId: params.roleId, script: run.script });
80
+ return result;
81
+ } catch (error) { return failed(error); }
504
82
  },
505
-
506
- /** 终止脚本:停程序但设备按最后一刻参数继续跑(不打断体验),并提醒 dsh 可续可停。 */
507
- async stopScript(runId) {
508
- const run = scriptRuns.get(String(runId));
509
- if (!run) return { ok: false, error: `没有运行中的脚本 runId=${runId}` };
510
- run.stopping = true;
511
- if (run.child) {
512
- try { run.child.kill('SIGTERM'); } catch { /* ignore */ }
513
- if (!await waitForChildExit(run.child, 1_000)) {
514
- try { run.child.kill('SIGKILL'); } catch { /* ignore */ }
515
- await waitForChildExit(run.child, 1_000);
516
- }
517
- }
518
- scriptRuns.delete(run.runId);
519
- persistToysRunning(run.workspace);
520
- const rt = runtimes.get(run.roleId);
521
- if (rt && rt.script?.runId === run.runId) { rt.script = null; rt.controller = 'idle'; }
522
- // 设备不断档:conn 仍按 rt.last 持续刷新;提醒 dsh 脚本已停、可续可停。
523
- if (rt) {
524
- const last = rt.last;
525
- const lastText = last.stroke
526
- ? `强度 ${last.intensity}、行程 ${last.stroke.join(',')}`
527
- : last.intensity
528
- ? `强度 ${last.intensity}`
529
- : '已停';
530
- void notify(rt, `[设备事件] 玩具操控脚本「${basename(run.script)}」已停止,设备保持最后一刻参数(${lastText})继续运行、不中断。`
531
- + '如需延续可再 toy_run_script 续一段,或 toy_control 调整;真正要停设备用 toy_control stop。', { priority: true });
532
- }
533
- return { ok: true, stopped: run.runId };
534
- },
535
-
536
- listScriptRuns() {
537
- return [...scriptRuns.values()].map((r) => ({
538
- runId: r.runId, roleId: r.roleId, script: r.script,
539
- scriptName: basename(r.script), pid: r.pid, startedAt: r.startedAt,
540
- }));
541
- },
542
-
543
- /**
544
- * toy 脚本运行中请求发言(脚本里 toy.wake)。构建 [设备事件] 情境唤醒导演,
545
- * 由导演判断此刻是否让角色开口(可说可静默)。
546
- */
547
- async wakeFromScript({ roleId, mood, topic, reason }) {
548
- if (!roleId) return { ok: false, error: '缺少 roleId' };
549
- const rt = runtime(roleId);
550
- const detail = [mood != null && `${mood}`.trim() ? `心情: ${mood}` : null,
551
- topic != null && `${topic}`.trim() ? `主题: ${topic}` : null,
552
- reason != null && `${reason}`.trim() ? `缘由: ${reason}` : null].filter(Boolean).join(';');
553
- const text = `[设备事件] 你的玩具操控脚本运行中想请你开口:${detail ? ` ${detail}` : ''}\n`
554
- + '你是导演:结合设备此刻的动作与对话氛围,判断现在是否适合让角色说一句自然的话(比如调情、回应 ta 的感受)。'
555
- + '适合就经 director_send 说,不适合可保持沉默。不要提及“设备事件/脚本/系统”。';
556
- return await notify(rt, text);
557
- },
558
-
559
- /** 角色删除/设备摘除时清理该角色的运行态。 */
560
- disposeRole: async (roleId) => {
561
- const rt = runtimes.get(roleId);
562
- if (rt) { clearPhase(rt); killScript(rt); await closeConn(rt); }
563
- activations.delete(roleId);
564
- runtimes.delete(roleId);
565
- wakes.delete(roleId);
566
- },
567
-
568
- /** 插件 teardown:断开全部 WS、终止脚本。 */
569
- async disposeAll() {
570
- for (const roleId of [...runtimes.keys()]) {
571
- const rt = runtimes.get(roleId);
572
- if (rt) { clearPhase(rt); killScript(rt); await closeConn(rt); }
573
- activations.delete(roleId);
574
- runtimes.delete(roleId);
575
- wakes.delete(roleId);
576
- }
577
- for (const run of [...scriptRuns.values()]) { try { run.child?.kill('SIGKILL'); } catch { /* ignore */ } }
578
- scriptRuns.clear();
83
+ async runScript({ roleId, deviceId, scriptPath }) {
84
+ try { const device = await select(roleId, deviceId); return service.runDeviceScript({ roleId, deviceId: device.id, scriptPath, directory: 'toys' }); }
85
+ catch (error) { return failed(error); }
579
86
  },
87
+ wakeFromScript({ roleId, ...input }) { return service.wake(roleId, input); },
88
+ async disposeRole(roleId) { await service.disposeRole(roleId); await Promise.all([...controllers.values()].map(item => item.disposeRole(roleId))); },
89
+ async disposeAll() { await service.disposeAll(); releaseBuiltin(); await Promise.all([...controllers.values()].map(item => item.disposeAll())); controllers.clear(); },
580
90
  };
581
91
  }