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.
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 }
@@ -385,6 +462,14 @@ export async function syncRoleMemory(role) {
385
462
  if (role.persona) {
386
463
  await atomicWrite(join(memory, '人物设定.md'), (personaMarkdown(role.persona) ?? '') + '\n');
387
464
  }
465
+ // 设备文档:角色授权设备 → memory/设备.md(preset 开场读);无授权 → 删除(撤选不残留)。
466
+ const devFile = join(memory, '设备.md');
467
+ const devDoc = await renderDeviceDoc(role);
468
+ if (devDoc) {
469
+ await atomicWrite(devFile, devDoc + '\n');
470
+ } else {
471
+ try { await rm(devFile, { force: true }); } catch { /* ignore */ }
472
+ }
388
473
  // 特殊记忆首次就位(已存在则保留 dsh 的编辑,不覆盖)。
389
474
  const taFile = join(memory, '关于TA.md');
390
475
  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) {
@@ -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
@@ -447,6 +447,206 @@ export function buildDirectorToolDefs(resolveCtx) {
447
447
  : { ok: false, error: res.error || '启动失败' };
448
448
  },
449
449
  },
450
+ // toy_status:查询角色可用设备状态
451
+ {
452
+ name: 'toy_status',
453
+ description: '查询当前角色已授权可用设备的状态:是否已激活(ta 是否发过分享链接)、当前运行状态'
454
+ + '(controller/last 参数/是否有脚本在跑)。需要操作设备前可先调用确认。',
455
+ parameters: {
456
+ type: 'object',
457
+ additionalProperties: false,
458
+ properties: {},
459
+ },
460
+ output: {
461
+ schema: {
462
+ type: 'object',
463
+ additionalProperties: false,
464
+ properties: {
465
+ ok: { type: 'boolean' },
466
+ devices: { type: 'array', items: { type: 'object' } },
467
+ error: { type: 'string' },
468
+ },
469
+ required: ['ok'],
470
+ },
471
+ render: (_args, value) => {
472
+ const v = value;
473
+ let text;
474
+ if (!v?.ok) text = `toy_status 失败: ${v?.error ?? '?'}`;
475
+ else if (!v.devices?.length) text = '该角色未配置可用设备。';
476
+ else {
477
+ const lines = v.devices.map((d) => `- ${d.alias}(${d.kind}):${d.activated ? '已激活' : '未激活——需 ta 发分享链接'}`
478
+ + (d.activated ? ` | 运行:${d.controller}${d.last ? ` 参数=${d.last.intensity !== 0 || d.last.stroke ? JSON.stringify(d.last) : ''}` : ''}${d.runId ? ` | 脚本=${d.runId}` : ''}` : ''));
479
+ text = ['可用设备:'].concat(lines).join('\n');
480
+ }
481
+ return [{ type: 'text', text }];
482
+ },
483
+ },
484
+ timeoutMs: 60_000,
485
+ async execute(_args, exec) {
486
+ const c = await resolveCtx(_args, exec);
487
+ if (!c.devices) return { ok: false, error: '设备服务不可用' };
488
+ if (!c.roleId) return { ok: false, error: '无角色上下文' };
489
+ return await c.devices.status(c.roleId);
490
+ },
491
+ },
492
+ // toy_control:定时/即时操控设备(工具调用模式)
493
+ {
494
+ name: 'toy_control',
495
+ description: '操控当前角色可用的玩具设备(行程+强度)。需要 ta 已发过一条新鲜分享链接(激活),否则会提示先请 ta 发。\n'
496
+ + '参数:intensity 强度 0-100;stroke 行程范围(用两个边界,取值 0/33/66/100,如 "0,100"=L1~L3 全行程往复、'
497
+ + '"0,66"=L1~L2 区间、"0,0"=停住;也可写区间名 "L1,L2");seconds 本次操作的时长(秒)。\n'
498
+ + '计时语义:到点后设备保持当前参数继续运行,系统会提醒你计时结束,可再次调用本工具调整或 stop。'
499
+ + '设备无自动停止——由你决定何时停(ta 要求停时必须停);停用 stop:true。\n'
500
+ + '注意:新一次调用会接管当前计时/脚本;单台设备一次只有一个在跑。',
501
+ parameters: {
502
+ type: 'object',
503
+ additionalProperties: false,
504
+ properties: {
505
+ device: { type: 'string', description: '可选:设备名/deviceId(角色只勾了一台可省)。' },
506
+ stroke: { type: 'string', description: '行程范围,如 "0,100"/"33,66"/"L1,L2"/"0,0"。' },
507
+ intensity: { type: 'number', description: '强度 0-100。' },
508
+ seconds: { type: 'number', description: '本次时长(秒);省略=立即设定不设计时。' },
509
+ stop: { type: 'boolean', description: 'true=停止设备(清计时/脚本并强度归零)。' },
510
+ },
511
+ },
512
+ output: {
513
+ schema: {
514
+ type: 'object',
515
+ additionalProperties: false,
516
+ properties: {
517
+ ok: { type: 'boolean' },
518
+ state: { type: 'object' },
519
+ seconds: { type: 'number' },
520
+ error: { type: 'string' },
521
+ },
522
+ required: ['ok'],
523
+ },
524
+ render: (_args, value) => {
525
+ const v = value;
526
+ let text;
527
+ if (!v?.ok) {
528
+ const err = v?.error ?? '?';
529
+ text = `toy_control 失败: ${err}${err.includes('激活') || err.includes('分享链接') ? '(让 ta 发一条新鲜分享链接即可)' : ''}`;
530
+ } else {
531
+ const s = v.state;
532
+ const last = s?.last;
533
+ const paramText = last ? `强度 ${last.intensity}${last.stroke ? `、行程 ${last.stroke.join(',')}` : ''}` : '无参数';
534
+ if (s?.controller === 'idle' && !last) text = '已停止设备。';
535
+ else text = v.seconds
536
+ ? `设备已设定,持续 ${v.seconds}s:${paramText}(到点保持参数并提醒你)`
537
+ : `设备已设定:${paramText}(无计时;停用 toy_control stop)`;
538
+ }
539
+ return [{ type: 'text', text }];
540
+ },
541
+ },
542
+ timeoutMs: 60_000,
543
+ async execute(args, exec) {
544
+ const c = await resolveCtx(args, exec);
545
+ if (!c.devices) return { ok: false, error: '设备服务不可用' };
546
+ if (!c.roleId) return { ok: false, error: '无角色上下文' };
547
+ if (args?.stop !== true && args?.intensity === undefined && args?.stroke === undefined) {
548
+ return { ok: false, error: '需提供 intensity 或 stroke(或 stop:true 停止)' };
549
+ }
550
+ const r = await c.devices.applyFromTool({
551
+ roleId: c.roleId,
552
+ deviceId: typeof args?.device === 'string' && args.device ? args.device : undefined,
553
+ intensity: args?.intensity,
554
+ stroke: args?.stroke,
555
+ seconds: args?.seconds,
556
+ stop: args?.stop === true,
557
+ });
558
+ if (!r?.ok) return { ok: false, error: r?.error || '失败' };
559
+ const out = { ok: true, state: r.state };
560
+ if (Number(args?.seconds) > 0) out.seconds = Number(args.seconds);
561
+ return noUndefined(out);
562
+ },
563
+ },
564
+ // toy_run_script:运行编排脚本(脚本模式)
565
+ {
566
+ name: 'toy_run_script',
567
+ description: '运行你在 workspace/toys/ 下写的一个设备操控脚本(.mjs/.js/.ts)。脚本是自由程序,运作方式完全由你设计:'
568
+ + '可以是编排好的动作流程,也可以随时间、对话或 ta 的反馈而变化、循环、分段推进等,随你创造。\n'
569
+ + '脚本侧只需关心设备参数:全局已预加载 toy 对象——await toy.set({ intensity, stroke }) 改变强度/行程、'
570
+ + 'await toy.sleep(毫秒) 控制节奏、toy.stop() 停止;不接触任何通信细节。'
571
+ + '合适时机可 await toy.wake({ mood, topic, reason }) 请导演开口(可说可静默)。'
572
+ + '脚本与运行日志完全透明可监管:管理台「玩具操控脚本」可查看运行状态与日志(toys/.logs/)。'
573
+ + '脚本自然结束即终止,结束时设备保持最后的参数继续运行并提醒你;中途停可用 stop=runId '
574
+ + '或 toy_control stop。每次只有一段脚本在跑,新的调用会接管。\n'
575
+ + '要先激活设备(ta 发分享链接)。templates/sample-toy.mjs 只是语法示例,勿照搬套路。',
576
+ parameters: {
577
+ type: 'object',
578
+ additionalProperties: false,
579
+ properties: {
580
+ script: { type: 'string', description: 'toys/ 下脚本文件名(省略找 main.*/index.*)。' },
581
+ reason: { type: 'string', description: '可选:本次启动/终止的缘由(记录)。' },
582
+ stop: { type: 'string', description: '可选:终止运行中的脚本 runId(提供时不再启动新脚本)。' },
583
+ },
584
+ },
585
+ output: {
586
+ schema: {
587
+ type: 'object',
588
+ additionalProperties: false,
589
+ properties: {
590
+ ok: { type: 'boolean' },
591
+ runId: { type: 'string' },
592
+ pid: { type: 'number' },
593
+ startedAt: { type: 'number' },
594
+ script: { type: 'string' },
595
+ stopped: { type: 'string' },
596
+ error: { type: 'string' },
597
+ },
598
+ required: ['ok'],
599
+ },
600
+ render: (_args, value) => {
601
+ const v = value;
602
+ let text;
603
+ if (!v?.ok) text = `toy_run_script 失败: ${v?.error ?? '?'}`;
604
+ else if (v.stopped) text = `已终止脚本 runId=${v.stopped}`;
605
+ else text = `toy 脚本已启动: ${v.script ?? ''}(runId=${v.runId}, pid=${v.pid})\n脚本在后台运行,自然结束=终止并保持最后参数;可用 toy_run_script stop=${v.runId} 或 toy_control stop 终止。`;
606
+ return [{ type: 'text', text }];
607
+ },
608
+ },
609
+ timeoutMs: 60_000,
610
+ async execute(args, exec) {
611
+ const c = await resolveCtx(args, exec);
612
+ if (!c.devices) return { ok: false, error: '设备服务不可用' };
613
+ if (!c.roleId) return { ok: false, error: '无角色上下文' };
614
+ // stop 模式
615
+ if (typeof args?.stop === 'string' && args.stop.trim()) {
616
+ const res = await c.devices.stopScript(args.stop.trim());
617
+ return res.ok ? { ok: true, stopped: res.stopped } : { ok: false, error: res.error || '终止失败' };
618
+ }
619
+ const ws = typeof c.workspaceOf === 'function' ? await c.workspaceOf() : null;
620
+ if (!ws) return { ok: false, error: '无角色工作区上下文' };
621
+ const toysDir = join(ws, 'toys');
622
+ let names = [];
623
+ try { names = (await readdir(toysDir)).filter((n) => /\.(mjs|js|ts)$/.test(n)); } catch { /* 目录不存在 */ }
624
+ let given = typeof args?.script === 'string' ? String(args.script).trim() : '';
625
+ let scriptPath;
626
+ if (given) {
627
+ const p = join(toysDir, given);
628
+ if (!existsSync(p)) return { ok: false, error: `toys/${given} 不存在(现有: ${names.join(', ') || '无'})` };
629
+ scriptPath = p;
630
+ } else {
631
+ const main = names.find((n) => /^(main|index)\./.test(n)) ?? names[0];
632
+ if (!main) return { ok: false, error: 'toys/ 下还没有脚本——先用文件工具新建一个 .mjs 再 toy_run_script(参考 templates/sample-toy.mjs)。' };
633
+ scriptPath = join(toysDir, main);
634
+ }
635
+ const role = c.persona && c.roleId ? await c.persona.loadRole(c.roleId).catch(() => null) : null;
636
+ const res = await c.devices.runScript({
637
+ roleId: c.roleId,
638
+ scriptPath,
639
+ workspace: ws,
640
+ httpApiToken: c.httpApiToken,
641
+ httpApiPath: c.httpApiPath,
642
+ openid: role?.binding?.openid,
643
+ reason: args?.reason,
644
+ });
645
+ return res.ok
646
+ ? { ok: true, runId: res.runId, pid: res.pid, startedAt: res.startedAt, script: res.script }
647
+ : { ok: false, error: res.error || '启动失败' };
648
+ },
649
+ },
450
650
  ];
451
651
  }
452
652
 
@@ -857,6 +1057,7 @@ export function registerDirectorTools(agentCtx, sessionId, deps) {
857
1057
  roleId: deps.roleId, httpApiToken: deps.httpApiToken, httpApiPath: deps.httpApiPath,
858
1058
  persona: deps.persona, log: deps.log, workspaceOf: deps.workspaceOf,
859
1059
  subagents: deps.subagents, llm: deps.llm,
1060
+ devices: deps.devices,
860
1061
  });
861
1062
  for (const def of buildDirectorToolDefs(resolveCtx))
862
1063
  tools.register(def);
@@ -892,6 +1093,7 @@ export function registerStandingTools(ctx, depsFor) {
892
1093
  roleId: deps.roleId, httpApiToken: deps.httpApiToken, httpApiPath: deps.httpApiPath,
893
1094
  persona: deps.persona, log: deps.log, workspaceOf: deps.workspaceOf,
894
1095
  subagents: deps.subagents, llm: deps.llm,
1096
+ devices: deps.devices,
895
1097
  };
896
1098
  };
897
1099
  for (const def of buildQQToolDefs(resolveCtx))
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)');
@@ -6,6 +6,7 @@ const views = { auth: $('#auth-view'), app: $('#app-view') };
6
6
  const editorView = $('#editor-view');
7
7
  const lifeView = $('#life-view');
8
8
  const memeView = $('#meme-view');
9
+ const deviceView = $('#device-view');
9
10
 
10
11
  let me = null;
11
12
  let roles = [];
@@ -19,6 +20,7 @@ function show(view) {
19
20
  editorView.classList.add('hidden');
20
21
  lifeView.classList.add('hidden');
21
22
  memeView.classList.add('hidden');
23
+ deviceView.classList.add('hidden');
22
24
  }
23
25
  function status(msg, isErr = false) {
24
26
  const bar = $('#status-bar');
@@ -196,6 +198,9 @@ function openEditor(rid) {
196
198
  fillBotForm(role);
197
199
  editorView.classList.remove('hidden');
198
200
  lifeView.classList.add('hidden');
201
+ memeView.classList.add('hidden');
202
+ deviceView.classList.add('hidden');
203
+ void renderDeviceChecks(p.devices || []);
199
204
  editorView.scrollIntoView({ behavior: 'smooth' });
200
205
  }
201
206
  function fillBotForm(role) {
@@ -223,6 +228,7 @@ $('#role-form').addEventListener('submit', async (e) => {
223
228
  speakingStyle: $('#f-speaking').value.trim(),
224
229
  relationship: $('#f-relationship').value.trim(),
225
230
  schedule: Object.fromEntries($('#f-schedule').value.split('\n').map((l) => l.trim()).filter(Boolean).map((l) => l.split('=').map((x) => x.trim()))),
231
+ devices: [...document.querySelectorAll('#f-devices input:checked')].map((x) => x.value),
226
232
  };
227
233
  const model = {
228
234
  provider: $('#f-provider').value.trim(),
@@ -262,6 +268,54 @@ $('#role-form').addEventListener('submit', async (e) => {
262
268
  } catch (err) { $('#editor-error').textContent = err.message; }
263
269
  });
264
270
 
271
+ /* ------------------------------- 我的设备 ------------------------------- */
272
+ async function renderDeviceChecks(selected = []) {
273
+ const box = $('#f-devices');
274
+ let list = [];
275
+ try { list = (await api('/api/me/devices')).devices || []; }
276
+ catch { box.innerHTML = '<span class="muted">加载设备失败</span>'; return; }
277
+ if (!list.length) { box.innerHTML = '<span class="muted">还没有设备——先点右上「我的设备」登记。</span>'; return; }
278
+ box.innerHTML = list.map((d) => `<label class="inline device-check"><input type="checkbox" value="${esc(d.id)}" ${(selected || []).includes(d.id) ? 'checked' : ''}> ${esc(d.alias)}<span class="muted">(${esc(d.kind)})</span></label>`).join('');
279
+ }
280
+ async function renderDevicePanel() {
281
+ const list = (await api('/api/me/devices')).devices || [];
282
+ const box = $('#device-list');
283
+ if (!list.length) { box.innerHTML = '<p class="muted">还没有设备。</p>'; return; }
284
+ box.innerHTML = list.map((d) => `<div class="row">
285
+ <span class="run-info">${esc(d.alias)} <span class="muted">(${esc(d.kind)})</span></span>
286
+ <button class="ghost danger device-del" data-id="${esc(d.id)}">删除</button>
287
+ </div>`).join('');
288
+ }
289
+ $('#btn-devices').addEventListener('click', () => {
290
+ editorView.classList.add('hidden');
291
+ lifeView.classList.add('hidden');
292
+ memeView.classList.add('hidden');
293
+ deviceView.classList.remove('hidden');
294
+ void renderDevicePanel();
295
+ });
296
+ $('#btn-close-devices').addEventListener('click', () => deviceView.classList.add('hidden'));
297
+ $('#device-add').addEventListener('click', async () => {
298
+ const alias = $('#device-alias').value.trim();
299
+ if (!alias) return;
300
+ try {
301
+ await api('/api/me/devices', 'POST', { alias, kind: 'monsterparty' });
302
+ $('#device-alias').value = '';
303
+ status('设备已登记');
304
+ await renderDevicePanel();
305
+ } catch (err) { status(err.message, true); }
306
+ });
307
+ $('#device-alias').addEventListener('keydown', (e) => { if (e.key === 'Enter') $('#device-add').click(); });
308
+ $('#device-list').addEventListener('click', async (e) => {
309
+ const btn = e.target.closest('button.device-del');
310
+ if (!btn) return;
311
+ if (!confirm('删除这台设备?它在各角色上的勾选也会移除。')) return;
312
+ try {
313
+ await api(`/api/me/devices/${encodeURIComponent(btn.dataset.id)}`, 'DELETE');
314
+ status('设备已删除');
315
+ await renderDevicePanel();
316
+ } catch (err) { status(err.message, true); }
317
+ });
318
+
265
319
  /* ------------------------------- QQ 机器人 ------------------------------- */
266
320
  $('#bot-form').addEventListener('submit', async (e) => {
267
321
  e.preventDefault();
@@ -341,6 +395,19 @@ async function refreshLife() {
341
395
  logs.innerHTML = (data.logs || []).length
342
396
  ? data.logs.map((n) => `<button class="log-btn" data-log="${esc(n)}">${esc(n)}</button>`).join('')
343
397
  : '<p class="muted">还没有运行记录(dsh 用 life_run 启动脚本后产生)</p>';
398
+ // 玩具操控脚本(toys/)
399
+ try {
400
+ const t = await api(`/api/me/roles/${lifeRoleId}/toys`);
401
+ $('#toy-running').innerHTML = (t.running || []).length
402
+ ? t.running.map((r) => `<div class="run-row"><span class="run-info">${esc(r.scriptName)} · PID ${esc(r.pid)}${r.startedAt ? ` · 启动 ${new Date(r.startedAt).toLocaleTimeString('zh-CN', { hour12: false })}` : ''}</span><button class="ghost danger toy-stop" data-run="${esc(r.runId)}">终止</button></div>`).join('')
403
+ : '<div class="muted">没有玩具脚本在运行(dsh 用 toy_run_script 运行)</div>';
404
+ $('#toy-scripts').innerHTML = (t.scripts || []).length
405
+ ? t.scripts.map((n) => `<button class="log-btn" data-toyscript="${esc(n)}">${esc(n)}</button>`).join('')
406
+ : '<div class="muted">toys/ 下还没有脚本</div>';
407
+ $('#toy-logs').innerHTML = (t.logs || []).length
408
+ ? t.logs.map((n) => `<button class="log-btn" data-toylog="${esc(n)}">${esc(n)}</button>`).join('')
409
+ : '<div class="muted">还没有玩具运行日志</div>';
410
+ } catch { /* 老版本无 toys 端点时忽略 */ }
344
411
  }
345
412
  let lifeLogTimer = null;
346
413
  let currentLifeLog = null;
@@ -391,6 +458,35 @@ $('#life-running').addEventListener('click', async (e) => {
391
458
  await refreshLife();
392
459
  } catch (err) { status(err.message, true); }
393
460
  });
461
+ $('#toy-running').addEventListener('click', async (e) => {
462
+ const btn = e.target.closest('button.toy-stop');
463
+ if (!btn) return;
464
+ try {
465
+ const r = await api(`/api/me/roles/${lifeRoleId}/toys/stop`, 'POST', { runId: btn.dataset.run });
466
+ status(r.ok ? '已终止玩具脚本' : (r.error || '终止失败'), !r.ok);
467
+ await refreshLife();
468
+ } catch (err) { status(err.message, true); }
469
+ });
470
+ $('#toy-logs').addEventListener('click', async (e) => {
471
+ const btn = e.target.closest('button[data-toylog]');
472
+ if (!btn) return;
473
+ try {
474
+ const txt = await (await fetch(`/api/me/roles/${lifeRoleId}/toys/log/${encodeURIComponent(btn.dataset.toylog)}`)).text();
475
+ $('#toy-source').classList.add('hidden');
476
+ $('#toy-log-body').textContent = txt;
477
+ $('#toy-log-body').classList.remove('hidden');
478
+ } catch (err) { status(err.message, true); }
479
+ });
480
+ $('#toy-scripts').addEventListener('click', async (e) => {
481
+ const btn = e.target.closest('button[data-toyscript]');
482
+ if (!btn) return;
483
+ try {
484
+ const txt = await (await fetch(`/api/me/roles/${lifeRoleId}/toys/script/${encodeURIComponent(btn.dataset.toyscript)}`)).text();
485
+ $('#toy-log-body').classList.add('hidden');
486
+ $('#toy-source').textContent = txt;
487
+ $('#toy-source').classList.remove('hidden');
488
+ } catch (err) { status(err.message, true); }
489
+ });
394
490
  $('#btn-close-life').addEventListener('click', () => { stopLifeLogPolling(); stopLifeRefresh(); currentLifeLog = null; lifeView.classList.add('hidden'); });
395
491
 
396
492
  /* ------------------------------- 表情包管理 ------------------------------- */
@@ -30,6 +30,7 @@
30
30
  <p class="muted" id="me-label"></p>
31
31
  </div>
32
32
  <div class="row">
33
+ <button id="btn-devices" class="ghost">我的设备</button>
33
34
  <button id="btn-password" class="ghost">改密码</button>
34
35
  <button id="btn-logout" class="ghost">退出</button>
35
36
  </div>
@@ -46,6 +47,20 @@
46
47
  <div id="role-list" class="role-list"></div>
47
48
  </section>
48
49
 
50
+ <!-- 我的设备库(用户级) -->
51
+ <section id="device-view" class="panel hidden">
52
+ <div class="card-head">
53
+ <h2>我的设备</h2>
54
+ <button id="btn-close-devices" class="ghost">关闭</button>
55
+ </div>
56
+ <p class="muted">登记你的玩具设备(先支持 MonsterParty「雷电」)。登记后在角色编辑页勾选「可用设备」;使用时让角色用户把 MonsterParty 的<strong>新鲜分享链接</strong>发给角色即可激活。分享链接单次有效,每次使用需重新生成。一台物理设备建议只勾选一个角色。</p>
57
+ <div class="row">
58
+ <input id="device-alias" placeholder="设备别名(如 雷电)">
59
+ <button type="button" id="device-add" class="ghost">添加</button>
60
+ </div>
61
+ <div id="device-list" class="log-list"></div>
62
+ </section>
63
+
49
64
  <!-- 新建 / 编辑角色 -->
50
65
  <section id="editor-view" class="panel hidden">
51
66
  <div class="card-head">
@@ -63,6 +78,10 @@
63
78
  <label>说话风格 <textarea id="f-speaking" rows="3"></textarea></label>
64
79
  <label>与 ta 的关系 <textarea id="f-relationship" rows="2"></textarea></label>
65
80
  <label>日程(HH:MM,每行一条,如 早安=08:00) <textarea id="f-schedule" rows="3" placeholder="早安=08:00&#10;晚安=23:00"></textarea></label>
81
+ <div class="device-pick">
82
+ <label>可用设备(勾选角色可操控的;未登记先去右上「我的设备」添加)</label>
83
+ <div id="f-devices" class="device-checkboxes muted">(加载中…)</div>
84
+ </div>
66
85
  </fieldset>
67
86
  <fieldset>
68
87
  <legend>模型</legend>
@@ -132,6 +151,15 @@
132
151
  <pre id="life-log-body" class="code hidden"></pre>
133
152
  <h3>快照备份(.backup/)</h3>
134
153
  <ul id="life-backups"></ul>
154
+ <h3>玩具操控脚本(toys/,dsh 用 toy_run_script 运行)</h3>
155
+ <div class="muted">运行中(可在运行表终止)</div>
156
+ <div id="toy-running" class="log-list"></div>
157
+ <div class="muted">脚本(toys/*.mjs)</div>
158
+ <div id="toy-scripts" class="log-list"></div>
159
+ <div class="muted">运行日志(toys/.logs/,点开查看)</div>
160
+ <div id="toy-logs" class="log-list"></div>
161
+ <pre id="toy-log-body" class="code hidden"></pre>
162
+ <pre id="toy-source" class="code hidden"></pre>
135
163
  </section>
136
164
  <!-- 表情包管理 -->
137
165
  <section id="meme-view" class="panel hidden">
@@ -49,3 +49,8 @@ ul { margin: 4px 0; padding-left: 20px; color: var(--muted); }
49
49
  .meme-meta { padding: 8px; display: flex; flex-direction: column; gap: 6px; }
50
50
  .meme-meta label { font-size: 12px; }
51
51
  .meme-meta input { font-size: 12px; padding: 5px 7px; }
52
+ /* 行内勾选(含设备勾选) */
53
+ label.inline { flex-direction: row; align-items: center; gap: 6px; width: auto; }
54
+ label.inline input { width: auto; }
55
+ .device-checkboxes { display: flex; flex-wrap: wrap; gap: 4px 18px; }
56
+ .device-check .muted { margin-left: 4px; }