pygmalion 0.1.8 → 0.1.9

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