pygmalion 0.1.11 → 0.1.13

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pygmalion",
3
- "version": "0.1.11",
3
+ "version": "0.1.13",
4
4
  "description": "Pygmalion:将 DeepSeek Harness(dsh)改造为「拟真 AI 好友」服务的 dsh 插件——QQ 官方机器人接入、文件系统双索引长期记忆、heartbeat+脚本+hook 主动交互,一次安装即用(含管理网页)",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/agent-life.js CHANGED
@@ -139,6 +139,26 @@ async function beginLifeLog({ workspace, script, startedAt }) {
139
139
  return logFile;
140
140
  }
141
141
 
142
+ /** 生活脚本的每次生命周期结束都回报导演。脚本自行调用 wake() 是“发生了什么”,
143
+ * 这里则是运行时的事实通知;二者不能互相替代。没有 HTTP 鉴权时静默降级,但绝不影响
144
+ * 脚本退出与日志落盘。 */
145
+ async function notifyLifeScriptEnded(opts, script, { exitCode, error } = {}) {
146
+ if (!opts?.baseUrl || !opts?.httpApiPath || !opts?.token || !opts?.openid) return;
147
+ const result = exitCode === 0 ? '正常结束' : error || `以退出码 ${exitCode ?? '未知'} 结束`;
148
+ try {
149
+ await fetch(`${opts.baseUrl}${opts.httpApiPath}/wakeup`, {
150
+ method: 'POST',
151
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${opts.token}` },
152
+ body: JSON.stringify({
153
+ channel: `c2c:${opts.openid}`,
154
+ reason: `生活脚本「${basename(script)}」${result}。`,
155
+ contextText: `[脚本结束] 生活脚本「${basename(script)}」${result}\n日志目录:life/.logs/`,
156
+ force: true,
157
+ }),
158
+ });
159
+ } catch { /* 通知失败不改变脚本已经结束这一事实 */ }
160
+ }
161
+
142
162
  async function readJson(file, fallback) {
143
163
  try { return JSON.parse(await readFile(file, 'utf8')); } catch { return fallback; }
144
164
  }
@@ -280,6 +300,7 @@ export async function startLifeScript(script, opts) {
280
300
  if (fd != null) { try { closeSync(fd); fd = null; } catch { /* ignore */ } }
281
301
  void (async () => {
282
302
  await recordLifeRun({ workspace: opts.workspace, script, startedAt, exitCode: null, output: out, stderr: err, logFile: logFile ?? undefined, error: `脚本启动失败: ${String(e)}` }).catch(() => {});
303
+ await notifyLifeScriptEnded(opts, script, { exitCode: null, error: `启动失败:${String(e?.message ?? e)}` });
283
304
  })();
284
305
  });
285
306
  child.on('close', async (code) => {
@@ -291,6 +312,10 @@ export async function startLifeScript(script, opts) {
291
312
  timeoutMs: opts.timeoutMs, logFile: logFile ?? undefined,
292
313
  ...(killed ? { error: `脚本超时(>${opts.timeoutMs}ms)已终止` } : code === 0 ? {} : { error: `脚本退出码 ${code}` }),
293
314
  }).catch(() => {});
315
+ await notifyLifeScriptEnded(opts, script, {
316
+ exitCode: killed ? null : code,
317
+ ...(killed ? { error: `超时后已终止` } : code === 0 ? {} : { error: `异常退出(退出码 ${code})` }),
318
+ });
294
319
  });
295
320
 
296
321
  // 返回前先落盘运行表:调用方拿到 ok 即保证重启后能按 .running.json 恢复。
@@ -353,7 +378,7 @@ export async function recoverLifeScripts(workspace) {
353
378
  for (const rec of Object.values(saved.runs)) {
354
379
  if (running.has(rec.runId)) continue;
355
380
  if (pidAlive(rec.pid)) {
356
- running.set(rec.runId, { runId: rec.runId, scriptPath: rec.scriptPath, scriptName: rec.scriptName, pid: rec.pid, startedAt: rec.startedAt, workspace, logFile: rec.logFile ?? undefined, child: null });
381
+ running.set(rec.runId, { runId: rec.runId, scriptPath: rec.scriptPath, scriptName: rec.scriptName, pid: rec.pid, startedAt: rec.startedAt, workspace, logFile: rec.logFile ?? undefined, opts: rec.opts, child: null });
357
382
  try {
358
383
  const manifest = await readLifeManifest(workspace);
359
384
  manifest.scripts[rec.scriptName] = { ...(manifest.scripts[rec.scriptName] || {}), path: rec.scriptPath, lastRunAt: rec.startedAt, state: 'running' };
@@ -420,6 +445,7 @@ export async function pruneDeadLifeScripts(workspace) {
420
445
  running.delete(rec.runId);
421
446
  dead++;
422
447
  await recordLifeRun({ workspace, script: rec.scriptPath, startedAt: rec.startedAt, exitCode: null, output: '', stderr: '', logFile: rec.logFile ?? undefined, error: '进程已退出(dsh 重启期间脚本结束)' }).catch(() => {});
448
+ await notifyLifeScriptEnded(rec.opts, rec.scriptPath, { exitCode: null, error: '已结束' });
423
449
  }
424
450
  if (dead) await persistRunning(workspace);
425
451
  return { dead };
@@ -447,7 +473,12 @@ export function stopLifeScript(runId) {
447
473
  const finish = (r) => { if (!done) { done = true; resolve(r); } };
448
474
  const settle = setTimeout(() => {
449
475
  try { process.kill(pid, 'SIGKILL'); } catch { /* 已退出,忽略 */ }
450
- setTimeout(() => { running.delete(String(runId)); void persistRunning(workspace); finish({ ok: true, runId }); }, 300);
476
+ setTimeout(() => {
477
+ running.delete(String(runId));
478
+ void persistRunning(workspace);
479
+ void notifyLifeScriptEnded(rec.opts, rec.scriptPath, { exitCode: null, error: '已终止' });
480
+ finish({ ok: true, runId });
481
+ }, 300);
451
482
  }, 1500);
452
483
  try { process.kill(pid, 'SIGTERM'); } catch (e) { clearTimeout(settle); finish({ ok: false, error: String(e) }); }
453
484
  });
package/src/config.js CHANGED
@@ -61,6 +61,7 @@ export const Config = Schema.object({
61
61
  lifeEnabled: Schema.boolean().default(true).description('生活脚本总开关'),
62
62
  lifeMaxPerDay: Schema.number().default(2).description('(已废弃:插件不再限制脚本运行次数)保留字段仅为兼容旧配置,不再被消费'),
63
63
  lifeIntervalMs: Schema.number().default(1800000).description('非零性破坏后重试提示「生活脚本未在运行」的最小间隔(毫秒,默认 30 分钟);每次 dsh 启动后首个心跳 tick 无视此间隔立刻提示一次,防跨重启陈旧节流压制'),
64
+ scriptReviewTime: Schema.string().default('02:00').description('每日脚本审阅时刻 HH:MM(空字符串=关闭)。到点唤醒导演审阅生活/玩具脚本及日志,独立于生活脚本非零性检查'),
64
65
  scriptWakeMinIntervalMs: Schema.number().default(600000).description('生活脚本 wake() 报事件后,同一角色再次唤醒 dsh 的最小间隔(毫秒),防脚本循环轰炸'),
65
66
  }).description('内置心跳(主动唤醒 + 沉默归档 + 非零性检查 + rewake 到期)'),
66
67
  bots: Schema.array(BotConfig).description('兼容旧部署格式:一次性迁移到 data/bots/,此后凭据在管理网页配置'),
@@ -51,17 +51,19 @@ export function deviceDocMarkdown(device) {
51
51
  lines.push(' - 其余按此推,如 "33,100"=中段偏上到拔出、"0,66" 附近舒适区;可结合强度调出 快而轻/缓而深/快而猛 等质感。');
52
52
  }
53
53
  lines.push('');
54
- lines.push('## 操控方式一:定时调用工具 toy_control');
54
+ lines.push('## 玩具操控');
55
+ lines.push('- 能使用则使用脚本控制玩具。脚本通过构建玩具运动的“波形”来控制体验:不是随机抽取参数,也不是把若干参数和固定时长简单串成阶段表。具体波形由你根据当下情境自行设计。');
56
+ lines.push('');
57
+ lines.push('### 定时调用工具 toy_control');
55
58
  lines.push('- 参数:intensity(强度)、stroke(行程范围)、seconds(本次时长的秒数)。');
56
59
  lines.push('- 到点后设备保持当前参数继续运行,系统会提醒你计时结束,可再次调用调整或 toy_control 停。');
57
60
  lines.push('');
58
- lines.push('## 操控方式二:编排脚本 toy_run_script');
59
- lines.push('- 在 workspace/toys/ 写一个 .mjs 脚本(可用 shell 或编辑器创建),再用 toy_run_script 运行。脚本是自由程序,运作方式由你设计——');
60
- lines.push(' 动作流程、节奏快慢、循环推进,或随 ta 的反应与对话气氛应变,都由你创造,不必套固定模式;');
61
+ lines.push('### 脚本 toy_run_script');
62
+ lines.push('- 在编写或运行前,先读取 workspace/toys/玩具脚本示例.mjs;设备激活时插件会将此参考文件放入 toys/。再在 workspace/toys/ 写自己的 .mjs 脚本,并用 toy_run_script 运行。');
61
63
  lines.push('- 脚本里只关心参数:await toy.set({ intensity, stroke }) 改变强度/行程、toy.sleep(毫秒) 控制节奏、toy.stop() 停止;');
62
64
  lines.push('- 脚本自然结束即终止,**结束时设备保持最后的参数继续运行、不中断**,系统会提醒你可续可停;');
63
- lines.push('- 合适时机可 await toy.wake({ mood, topic, reason }) 请你在脚本进行中开口(可说可静默);');
64
- lines.push('- 脚本无需也不可接触任何通信细节。templates/sample-toy.mjs 仅作语法示例。');
65
+ lines.push('- 每个玩具脚本都必须在其自行判断的合适位置调用 await toy.wake({ mood, topic, reason }),让你感知脚本中的变化并决定是否开口;');
66
+ lines.push('- 脚本无需也不可接触任何通信细节。');
65
67
  lines.push('');
66
68
  return lines.join('\n');
67
69
  }
@@ -15,6 +15,40 @@ import { parseLink as parseMp, resolveSession as resolveMp, MonsterPartyConn, MO
15
15
 
16
16
  const DEFAULT_BASE = 'http://127.0.0.1:3080';
17
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
+ }
18
52
 
19
53
  /** toy 脚本 helper:注入 globalThis.toy({ set/stop/sleep }),经 HTTP /toycmd 下发参数。 */
20
54
  const TOY_HELPER_SOURCE = `// auto-generated by pygmalion (device toy helper). do not edit.
@@ -244,6 +278,7 @@ export function createDeviceManager(deps) {
244
278
  async activate(roleId, token, { openid } = {}) {
245
279
  const role = await roleOf(roleId);
246
280
  if (!role?.persona) return { ok: false, error: '角色不存在', code: 'no-role' };
281
+ ensureToyReference(role.workspace);
247
282
  if (role.binding?.openid && openid && role.binding.openid !== openid)
248
283
  return { ok: false, error: '非设备拥有者', code: 'not-owner' };
249
284
  // 匹配该角色授权中的 monsterparty 设备(链接可能来自任一授权设备,单台场景直接命中)
@@ -355,6 +390,7 @@ export function createDeviceManager(deps) {
355
390
  if (!role?.persona) return { ok: false, error: '角色不存在' };
356
391
  // 校验脚本位于 workspace/toys/ 内且存在
357
392
  const toysDir = join(workspace, 'toys');
393
+ ensureToyReference(workspace);
358
394
  const full = resolve(scriptPath);
359
395
  const toysRoot = resolve(toysDir) + sep;
360
396
  if (!full.startsWith(toysRoot)) return { ok: false, error: '脚本必须在 workspace/toys/ 目录内' };
@@ -408,10 +444,12 @@ export function createDeviceManager(deps) {
408
444
 
409
445
  child.on('error', (e) => {
410
446
  warn('toy script error %s: %s', runId, e.message);
447
+ const stillCurrent = rt.script?.runId === runId;
411
448
  if (rt.script?.runId === runId) { rt.script = null; rt.controller = 'idle'; }
412
449
  scriptRuns.delete(runId);
413
450
  persistToysRunning(workspace);
414
451
  if (fd != null) { try { closeSync(fd); } catch { /* ignore */ } }
452
+ if (stillCurrent) void notify(rt, `[脚本结束] 玩具脚本「${basename(full)}」启动失败:${e.message}\n日志目录:toys/.logs/`);
415
453
  });
416
454
  child.on('close', (code) => {
417
455
  if (fd != null) { try { closeSync(fd); } catch { /* ignore */ } }
package/src/heartbeat.js CHANGED
@@ -9,7 +9,7 @@
9
9
  import { join } from 'node:path';
10
10
  import { readFile, readdir } from 'node:fs/promises';
11
11
  import { listRunningLifeScripts, recoverLifeScripts, pruneDeadLifeScripts } from './agent-life.js';
12
- import { wakeupSession, archiveWakeup } from './wakeup.js';
12
+ import { wakeupSession, archiveWakeup, buildScriptReviewContext } from './wakeup.js';
13
13
  import { classifyStagedMemes, collectMemes, resolveVisionConfig, withMemeLock } from './meme-worker.js';
14
14
  import { listMemes } from './memebox.js';
15
15
  import { activeSessionFile } from './active-session.js';
@@ -291,7 +291,7 @@ export function createHeartbeatScheduler(deps) {
291
291
  * 节流(warnIntervalMs)后唤醒 dsh,让它创作角色生活经历并程序化为脚本(life_run 启动)。
292
292
  * 插件不限制脚本运行时长/次数;「非零」由 dsh 保证。撞车/静默由 wakeupSession 处理。
293
293
  */
294
- async function lifeTick(ctxs, now) {
294
+ async function lifeTick(ctxs, now) {
295
295
  if (config.heartbeat?.lifeEnabled === false) return;
296
296
  const ts = now.getTime();
297
297
  const warnIntervalMs = config.heartbeat?.lifeIntervalMs ?? 3 * 3600 * 1000;
@@ -324,7 +324,32 @@ export function createHeartbeatScheduler(deps) {
324
324
  }
325
325
  // 首个 tick 已执行(无论是否唤醒),之后恢复节流。
326
326
  freshLife = false;
327
- }
327
+ }
328
+
329
+ /** 每日独立审阅:不以运行脚本数量作为触发条件。 */
330
+ async function scriptReviewTick(ctxs, now) {
331
+ const at = String(config.heartbeat?.scriptReviewTime ?? '02:00').trim();
332
+ if (!at || !/^([01]\d|2[0-3]):[0-5]\d$/.test(at)) return;
333
+ if (nowHm(now) < at) return;
334
+ const date = today(now);
335
+ for (const ctx of ctxs) {
336
+ const { role, openid, pipeline } = ctx;
337
+ if (role.proactive?.lifeEnabled === false) continue;
338
+ if (lastActivityByOpenid(pipeline.routes)[openid] === undefined) continue;
339
+ if (role.state?.lastScriptReviewDate === date) continue;
340
+ try {
341
+ const text = buildScriptReviewContext({ personaName: role.persona?.name, now });
342
+ const r = await wakeupSession(wakeBaseFor(pipeline), {
343
+ target: { kind: 'c2c', userId: openid }, reason: '每日脚本审阅', contextText: text, force: true,
344
+ });
345
+ // wakeupSession 因撞车跳过时不记完成,下一 tick 会重试;成功(即使导演沉默)才算审阅已送达。
346
+ if (r?.ok) {
347
+ await persona.saveRoleField(role.roleId, 'state', { ...(role.state || {}), lastScriptReviewDate: date });
348
+ log?.info?.('pygmalion heartbeat: daily script review %s', role.roleId);
349
+ }
350
+ } catch (e) { log?.warn?.('pygmalion heartbeat script review %s failed: %o', role.roleId, e); }
351
+ }
352
+ }
328
353
 
329
354
  /**
330
355
  * ⑤ 免打扰时段推迟的唤醒:脚本在安静时段调用 /wakeup 时,插件把唤醒写入
@@ -342,7 +367,8 @@ export function createHeartbeatScheduler(deps) {
342
367
  const r = await wakeupSession(wakeBaseFor(pipeline), {
343
368
  target: { kind: 'c2c', userId: openid },
344
369
  reason: dw.reason || '免打扰时段推迟的脚本唤醒',
345
- memoryHint: dw.memoryHint,
370
+ memoryHint: dw.memoryHint,
371
+ contextText: dw.contextText,
346
372
  kind: dw.kind,
347
373
  mood: dw.mood,
348
374
  topic: dw.topic,
@@ -376,7 +402,8 @@ export function createHeartbeatScheduler(deps) {
376
402
  log?.info?.('pygmalion heartbeat: wakeup %s (%s) ok=%s', w.ctx.role.roleId, w.rule, Boolean(r?.ok));
377
403
  } catch (e) { log?.warn?.('pygmalion heartbeat wakeup %s failed: %o', w.ctx.role.roleId, e); }
378
404
  }
379
- await lifeTick(ctxs, now);
405
+ await lifeTick(ctxs, now);
406
+ await scriptReviewTick(ctxs, now);
380
407
  await rewakeTick(ctxs, now);
381
408
  await deferredWakeupTick(ctxs, now);
382
409
  for (const a of await computeArchives(ctxs, now)) {
package/src/http-api.js CHANGED
@@ -261,6 +261,11 @@ async function handleWakeup(deps, res, body) {
261
261
  sendJson(res, 400, { ok: false, error: 'memoryHint(可选)必须是字符串:给 dsh 的记忆提示' });
262
262
  return;
263
263
  }
264
+ const contextText = body.contextText;
265
+ if (contextText !== undefined && typeof contextText !== 'string') {
266
+ sendJson(res, 400, { ok: false, error: 'contextText(可选)必须是字符串:完整 dsh 情境' });
267
+ return;
268
+ }
264
269
  const force = body.force;
265
270
  if (force !== undefined && typeof force !== 'boolean') {
266
271
  sendJson(res, 400, { ok: false, error: 'force(可选)必须是布尔值:true 跳过撞车检测' });
@@ -298,7 +303,7 @@ async function handleWakeup(deps, res, body) {
298
303
  try {
299
304
  const role = await deps.persona.loadRole(deps.roleId);
300
305
  if (role && inQuietHours(role.proactive?.quietHours || [])) {
301
- const state = { ...(role.state || {}), deferredWakeup: { reason, memoryHint, kind, mood, topic, force, atMs: Date.now() } };
306
+ const state = { ...(role.state || {}), deferredWakeup: { reason, memoryHint, contextText, kind, mood, topic, force, atMs: Date.now() } };
302
307
  if (kind === 'script-hook') state.lastScriptWakeAt = Date.now();
303
308
  await deps.persona.saveRoleField(deps.roleId, 'state', state);
304
309
  sendJson(res, 200, { ok: true, deferred: true, reason: 'quiet-hours', woken: false });
@@ -317,7 +322,7 @@ async function handleWakeup(deps, res, body) {
317
322
  activityAt: deps.activityAt,
318
323
  withinChatWindowMs: deps.withinChatWindowMs,
319
324
  log: deps.log,
320
- }, { target, reason, memoryHint, force, kind, mood, topic });
325
+ }, { target, reason, memoryHint, contextText, force, kind, mood, topic });
321
326
  if (result.ok === false) {
322
327
  sendJson(res, 200, result); // collision/skip is a normal outcome, not an error
323
328
  return;
@@ -501,4 +506,4 @@ export function createHttpApiHandler(deps) {
501
506
  }
502
507
  };
503
508
  }
504
- //# sourceMappingURL=http-api.js.map
509
+ //# sourceMappingURL=http-api.js.map
package/src/tools.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { targetOfSession, SESSION_PREFIX } from './inbound.js';
2
2
  import { readdir, readFile } from 'node:fs/promises';
3
3
  import { existsSync } from 'node:fs';
4
- import { join } from 'node:path';
4
+ import { join } from 'node:path';
5
+ import { TOY_REFERENCE_NAME } from './devices/manager.mjs';
5
6
  import { findLifeScript, listLifeScripts, startLifeScript, stopLifeScript, readLifeManifest, snapshotLifeScript } from './agent-life.js';
6
7
  import { sessionFileFor } from './active-session.js';
7
8
  import { refreshRawRecordFromSession, charLabelOf } from './memory-write.js';
@@ -586,18 +587,17 @@ export function buildDirectorToolDefs(resolveCtx) {
586
587
  return noUndefined(out);
587
588
  },
588
589
  },
589
- // toy_run_script:运行编排脚本(脚本模式)
590
+ // toy_run_script:运行玩具操控脚本
590
591
  {
591
592
  name: 'toy_run_script',
592
- description: '运行你在 workspace/toys/ 下写的一个设备操控脚本(.mjs/.js/.ts)。脚本是自由程序,运作方式完全由你设计:'
593
- + '可以是编排好的动作流程,也可以随时间、对话或 ta 的反馈而变化、循环、分段推进等,随你创造。\n'
593
+ description: '运行你在 workspace/toys/ 下写的一个设备操控脚本(.mjs/.js/.ts)。应使用脚本构建玩具运动的“波形”来控制玩具:不是随机抽取参数,也不是把若干参数和固定时长简单串成阶段表;具体波形由你自行设计。编写或运行前必须先读取 workspace/toys/玩具脚本示例.mjs。\n'
594
594
  + '脚本侧只需关心设备参数:全局已预加载 toy 对象——await toy.set({ intensity, stroke }) 改变强度/行程、'
595
595
  + 'await toy.sleep(毫秒) 控制节奏、toy.stop() 停止;不接触任何通信细节。'
596
- + '合适时机可 await toy.wake({ mood, topic, reason }) 请导演开口(可说可静默)。'
596
+ + '每个玩具脚本必须在自行判断的合适位置调用 await toy.wake({ mood, topic, reason }),请导演感知脚本中的变化并决定是否开口。'
597
597
  + '脚本与运行日志完全透明可监管:管理台「玩具操控脚本」可查看运行状态与日志(toys/.logs/)。'
598
598
  + '脚本自然结束即终止,结束时设备保持最后的参数继续运行并提醒你;中途停可用 stop=runId '
599
599
  + '或 toy_control stop。每次只有一段脚本在跑,新的调用会接管。\n'
600
- + '要先激活设备(ta 发分享链接)。templates/sample-toy.mjs 只是语法示例,勿照搬套路。',
600
+ + '要先激活设备(ta 发分享链接);激活后参考脚本会位于 toys/玩具脚本示例.mjs。',
601
601
  parameters: {
602
602
  type: 'object',
603
603
  additionalProperties: false,
@@ -645,19 +645,20 @@ export function buildDirectorToolDefs(resolveCtx) {
645
645
  if (!ws) return { ok: false, error: '无角色工作区上下文' };
646
646
  const toysDir = join(ws, 'toys');
647
647
  let names = [];
648
- try { names = (await readdir(toysDir)).filter((n) => /\.(mjs|js|ts)$/.test(n)); } catch { /* 目录不存在 */ }
648
+ try { names = (await readdir(toysDir)).filter((n) => /\.(mjs|js|ts)$/.test(n) && n !== TOY_REFERENCE_NAME); } catch { /* 目录不存在 */ }
649
649
  let given = typeof args?.script === 'string' ? String(args.script).trim() : '';
650
650
  let scriptPath;
651
- if (given) {
652
- const p = join(toysDir, given);
653
- if (!existsSync(p)) return { ok: false, error: `toys/${given} 不存在(现有: ${names.join(', ') || '无'})` };
654
- scriptPath = p;
651
+ if (given) {
652
+ if (given === TOY_REFERENCE_NAME) return { ok: false, error: '玩具脚本示例仅供先阅读参考,请新建自己的脚本后再运行。' };
653
+ const p = join(toysDir, given);
654
+ if (!existsSync(p)) return { ok: false, error: `toys/${given} 不存在(现有: ${names.join(', ') || '无'})` };
655
+ scriptPath = p;
655
656
  } else {
656
657
  const main = names.find((n) => /^(main|index)\./.test(n)) ?? names[0];
657
658
  if (!main) return { ok: false, error: 'toys/ 下还没有脚本——先用文件工具新建一个 .mjs 再 toy_run_script(参考 templates/sample-toy.mjs)。' };
658
659
  scriptPath = join(toysDir, main);
659
- }
660
- const role = c.persona && c.roleId ? await c.persona.loadRole(c.roleId).catch(() => null) : null;
660
+ }
661
+ const role = c.persona && c.roleId ? await c.persona.loadRole(c.roleId).catch(() => null) : null;
661
662
  const res = await c.devices.runScript({
662
663
  roleId: c.roleId,
663
664
  scriptPath,
package/src/wakeup.js CHANGED
@@ -88,7 +88,7 @@ export function buildScriptEventContext({ event, mood, topic, reason, personaNam
88
88
  * “生活窗口”情境:非零性破坏时唤醒导演(没有任何生活脚本在运行),让 dsh 创作角色
89
89
  * 生活经历并程序化为脚本。插件不限制脚本运行时长/次数;“非零”由 dsh 保证。
90
90
  */
91
- export function buildLifeWindowContext({ reason, personaName, hasLifeScript, now = new Date() }) {
91
+ export function buildLifeWindowContext({ reason, personaName, hasLifeScript, now = new Date() }) {
92
92
  const parts = [
93
93
  '[生活窗口] 时间:' + nowText(now),
94
94
  ];
@@ -115,7 +115,15 @@ export function buildLifeWindowContext({ reason, personaName, hasLifeScript, now
115
115
  parts.push('');
116
116
  parts.push('像真实生活那样自然地行动:可以开口,也可以安静;不要念设定,不要提及“导演 / 脚本 / 系统”。');
117
117
  return parts.join('\n');
118
- }
118
+ }
119
+
120
+ export function buildScriptReviewContext({ personaName, now = new Date() }) {
121
+ const parts = ['[脚本审阅] 时间:' + nowText(now)];
122
+ if (personaName != null && personaName.length > 0) parts.push('角色:' + personaName);
123
+ parts.push('', '请审阅当前运行中的脚本及相关日志。');
124
+ parts.push('审阅目标:丰富角色交互体验,使用户更能感到角色是活生生的人,有自己的生活,并且符合其社会身份和人设。');
125
+ return parts.join('\n');
126
+ }
119
127
 
120
128
  /**
121
129
  * 归档唤醒:注入一次归档任务并唤醒 dsh(不发送任何消息给用户)。
@@ -425,26 +425,160 @@ $('#btn-del-bot').addEventListener('click', async () => {
425
425
  } catch (err) { $('#bot-error').textContent = err.message; }
426
426
  });
427
427
 
428
- /* ------------------------------- 脚本监管 ------------------------------- */
429
- let lifeRefreshTimer = null;
430
- function startLifeRefresh() {
431
- if (lifeRefreshTimer) return;
432
- lifeRefreshTimer = setInterval(refreshLife, 3000);
428
+ /* ------------------------------- 脚本监管 ------------------------------- */
429
+ let lifeRefreshTimer = null;
430
+ let scriptLogTimer = null;
431
+ let currentScriptLog = null;
432
+ const scriptSelection = {
433
+ life: { kind: null, name: null },
434
+ toy: { kind: null, name: null },
435
+ };
436
+
437
+ function selectScriptSpace(space) {
438
+ document.querySelectorAll('[data-script-space]').forEach((button) => {
439
+ const active = button.dataset.scriptSpace === space;
440
+ button.classList.toggle('active', active);
441
+ button.setAttribute('aria-selected', String(active));
442
+ });
443
+ $('#script-space-life').classList.toggle('hidden', space !== 'life');
444
+ $('#script-space-toy').classList.toggle('hidden', space !== 'toy');
445
+ }
446
+
447
+ function selectAssetKind(group, kind) {
448
+ const space = $(`#script-space-${group}`);
449
+ space.querySelectorAll('[data-asset-kind]').forEach((button) => {
450
+ const active = button.dataset.assetKind === kind;
451
+ button.classList.toggle('active', active);
452
+ button.setAttribute('aria-selected', String(active));
453
+ });
454
+ space.querySelectorAll('[data-asset-panel]').forEach((panel) => {
455
+ panel.classList.toggle('hidden', panel.dataset.assetPanel !== kind);
456
+ });
457
+ }
458
+
459
+ async function showFirstLog(group) {
460
+ if (scriptSelection[group].name || window.matchMedia('(max-width: 700px)').matches) return;
461
+ const attribute = group === 'life' ? 'data-log' : 'data-toylog';
462
+ const first = $(`#${group}-logs button[${attribute}]`);
463
+ if (first) await showScriptLog(group, first.getAttribute(attribute));
464
+ }
465
+
466
+ function resetInspector(group) {
467
+ scriptSelection[group] = { kind: null, name: null };
468
+ $(`#${group}-inspector-kind`).textContent = 'PREVIEW';
469
+ $(`#${group}-inspector-title`).textContent = '选择一条日志或脚本';
470
+ $(`#${group}-inspector-state`).textContent = '日志打开后自动追踪更新';
471
+ $(`#${group}-preview-empty`).classList.remove('hidden');
472
+ $(`#${group}-source`).classList.add('hidden');
473
+ $(`#${group}-log-body`).classList.add('hidden');
474
+ }
475
+
476
+ function syncSelectedResource(group) {
477
+ const selected = scriptSelection[group];
478
+ $(`#script-space-${group}`).querySelectorAll('[data-resource-kind]').forEach((button) => {
479
+ button.classList.toggle('active', button.dataset.resourceKind === selected.kind && button.dataset.resourceName === selected.name);
480
+ });
481
+ }
482
+
483
+ function showInspector(group, kind, name, text, live = false) {
484
+ scriptSelection[group] = { kind, name };
485
+ const isLog = kind === 'log';
486
+ $(`#${group}-inspector-kind`).textContent = isLog ? 'LOG OUTPUT' : 'SOURCE CODE';
487
+ $(`#${group}-inspector-title`).textContent = name;
488
+ $(`#${group}-inspector-state`).textContent = isLog && live ? '实时追踪中 · 每 2 秒更新' : (isLog ? '运行日志' : '只读源码');
489
+ $(`#${group}-preview-empty`).classList.add('hidden');
490
+ const source = $(`#${group}-source`);
491
+ const log = $(`#${group}-log-body`);
492
+ source.classList.toggle('hidden', isLog);
493
+ log.classList.toggle('hidden', !isLog);
494
+ (isLog ? log : source).textContent = text;
495
+ syncSelectedResource(group);
496
+ if (window.matchMedia('(max-width: 700px)').matches) {
497
+ $(`#script-space-${group} .inspector-panel`).scrollIntoView({ behavior: 'smooth', block: 'start' });
498
+ }
499
+ }
500
+
501
+ async function fetchScriptText(url) {
502
+ const response = await fetch(url);
503
+ const text = await response.text();
504
+ if (!response.ok) {
505
+ try { throw new Error(JSON.parse(text).error || `HTTP ${response.status}`); }
506
+ catch (err) { if (err instanceof SyntaxError) throw new Error(`HTTP ${response.status}`); throw err; }
507
+ }
508
+ return text;
509
+ }
510
+
511
+ function startScriptLogPolling() {
512
+ if (scriptLogTimer) return;
513
+ scriptLogTimer = setInterval(async () => {
514
+ if (!currentScriptLog || lifeView.classList.contains('hidden')) return;
515
+ const { group, name } = currentScriptLog;
516
+ const area = group === 'life' ? 'life' : 'toys';
517
+ try {
518
+ const text = await fetchScriptText(`/api/me/roles/${lifeRoleId}/${area}/log/${encodeURIComponent(name)}`);
519
+ if (currentScriptLog?.group === group && currentScriptLog?.name === name) $(`#${group}-log-body`).textContent = text;
520
+ } catch { /* 单次刷新失败忽略,下一轮再试 */ }
521
+ }, 2000);
522
+ }
523
+
524
+ function stopScriptLogPolling() {
525
+ if (scriptLogTimer) { clearInterval(scriptLogTimer); scriptLogTimer = null; }
526
+ currentScriptLog = null;
527
+ }
528
+
529
+ async function showScriptLog(group, name) {
530
+ const area = group === 'life' ? 'life' : 'toys';
531
+ try {
532
+ const text = await fetchScriptText(`/api/me/roles/${lifeRoleId}/${area}/log/${encodeURIComponent(name)}`);
533
+ selectScriptSpace(group);
534
+ selectAssetKind(group, 'logs');
535
+ currentScriptLog = { group, name };
536
+ showInspector(group, 'log', name, text, true);
537
+ startScriptLogPolling();
538
+ } catch (err) { status(err.message, true); }
539
+ }
540
+
541
+ async function showScriptSource(group, name) {
542
+ const area = group === 'life' ? 'life' : 'toys';
543
+ try {
544
+ const text = await fetchScriptText(`/api/me/roles/${lifeRoleId}/${area}/script/${encodeURIComponent(name)}`);
545
+ if (currentScriptLog?.group === group) currentScriptLog = null;
546
+ selectScriptSpace(group);
547
+ selectAssetKind(group, 'scripts');
548
+ showInspector(group, 'source', name, text);
549
+ } catch (err) { status(err.message, true); }
550
+ }
551
+
552
+ function resourceButton(group, kind, name, attribute) {
553
+ const active = scriptSelection[group].kind === kind && scriptSelection[group].name === name ? ' active' : '';
554
+ return `<button class="log-btn${active}" type="button" ${attribute}="${esc(name)}" data-resource-kind="${kind}" data-resource-name="${esc(name)}"><span class="item-name">${esc(name)}</span></button>`;
555
+ }
556
+
557
+ function startLifeRefresh() {
558
+ if (lifeRefreshTimer) return;
559
+ lifeRefreshTimer = setInterval(refreshLife, 3000);
433
560
  }
434
561
  function stopLifeRefresh() {
435
562
  if (lifeRefreshTimer) { clearInterval(lifeRefreshTimer); lifeRefreshTimer = null; }
436
563
  }
437
564
  async function openLife(rid) {
438
- lifeRoleId = rid;
439
- const role = roles.find((r) => r.roleId === rid);
565
+ lifeRoleId = rid;
566
+ const role = roles.find((r) => r.roleId === rid);
440
567
  $('#life-role-name').textContent = role?.persona?.name || '未命名角色';
441
568
  rolesView.classList.add('hidden');
442
569
  editorView.classList.add('hidden');
443
570
  lifeView.classList.remove('hidden');
444
571
  pageTitle.textContent = '脚本监管';
445
- lifeView.scrollIntoView({ behavior: 'smooth' });
446
- await refreshLife();
447
- startLifeRefresh();
572
+ selectScriptSpace('life');
573
+ selectAssetKind('life', 'logs');
574
+ selectAssetKind('toy', 'logs');
575
+ resetInspector('life');
576
+ resetInspector('toy');
577
+ stopScriptLogPolling();
578
+ lifeView.scrollIntoView({ behavior: 'smooth', block: 'start' });
579
+ await refreshLife();
580
+ await showFirstLog('life');
581
+ startLifeRefresh();
448
582
  }
449
583
  function fmtDur(ms) {
450
584
  const s = Math.max(0, Math.floor(ms / 1000));
@@ -456,9 +590,10 @@ function fmtDur(ms) {
456
590
  async function refreshLife() {
457
591
  const data = await api(`/api/me/roles/${lifeRoleId}/life`);
458
592
  $('#life-manifest').textContent = JSON.stringify(data.manifest || {}, null, 2);
459
- // 运行中脚本(dsh 用 life_run 启动;由脚本自己决定何时结束,插件只监管)
460
- const running = data.running || [];
461
- $('#life-running').innerHTML = running.length
593
+ // 运行中脚本(dsh 用 life_run 启动;由脚本自己决定何时结束,插件只监管)
594
+ const running = data.running || [];
595
+ $('#life-running-count').textContent = `${running.length} 个运行中`;
596
+ $('#life-running').innerHTML = running.length
462
597
  ? running.map((r) => `<div class="run-row">
463
598
  <span class="run-info">${esc(r.scriptName)} · PID ${esc(r.pid)} · 已运行 ${fmtDur(r.elapsedMs)}</span>
464
599
  <button class="ghost run-log" data-log="${esc(r.logName)}">日志</button>
@@ -466,72 +601,58 @@ async function refreshLife() {
466
601
  </div>`).join('')
467
602
  : '<div class="muted">没有脚本在运行(dsh 用 life_run 启动,可长驻循环)</div>';
468
603
  // 脚本清单(点击查看源码)
469
- const scripts = Object.keys(data.manifest?.scripts || {});
470
- $('#life-scripts').innerHTML = scripts.length
471
- ? scripts.map((n) => `<button class="log-btn" data-script="${esc(n)}">${esc(n)}</button>`).join('')
472
- : '<li class="muted">life/ 下还没有脚本(由 dsh 创建并运行;内容与日志在管理页可见)</li>';
473
- $('#life-backups').innerHTML = (data.backups || []).length
474
- ? data.backups.map((b) => `<li>${esc(b)}</li>`).join('')
475
- : '<li class="muted">暂无备份(脚本每次被 life_run 启动前会自动快照当前版本)</li>';
476
- const logs = $('#life-logs');
477
- logs.innerHTML = (data.logs || []).length
478
- ? data.logs.map((n) => `<button class="log-btn" data-log="${esc(n)}">${esc(n)}</button>`).join('')
479
- : '<p class="muted">还没有运行记录(dsh 用 life_run 启动脚本后产生)</p>';
604
+ const scripts = Object.keys(data.manifest?.scripts || {});
605
+ $('#life-script-count').textContent = scripts.length;
606
+ $('#life-scripts').innerHTML = scripts.length
607
+ ? scripts.map((n) => resourceButton('life', 'source', n, 'data-script')).join('')
608
+ : '<div class="muted">life/ 下还没有脚本</div>';
609
+ $('#life-backup-count').textContent = (data.backups || []).length;
610
+ $('#life-backups').innerHTML = (data.backups || []).length
611
+ ? data.backups.map((b) => `<div class="backup-item" title="${esc(b)}">${esc(b)}</div>`).join('')
612
+ : '<div class="muted">暂无备份</div>';
613
+ const logs = $('#life-logs');
614
+ $('#life-log-count').textContent = (data.logs || []).length;
615
+ logs.innerHTML = (data.logs || []).length
616
+ ? data.logs.map((n) => resourceButton('life', 'log', n, 'data-log')).join('')
617
+ : '<div class="muted">还没有运行日志</div>';
480
618
  // 玩具操控脚本(toys/)
481
619
  try {
482
- const t = await api(`/api/me/roles/${lifeRoleId}/toys`);
483
- $('#toy-running').innerHTML = (t.running || []).length
484
- ? 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('')
485
- : '<div class="muted">没有玩具脚本在运行(dsh 用 toy_run_script 运行)</div>';
486
- $('#toy-scripts').innerHTML = (t.scripts || []).length
487
- ? t.scripts.map((n) => `<button class="log-btn" data-toyscript="${esc(n)}">${esc(n)}</button>`).join('')
488
- : '<div class="muted">toys/ 下还没有脚本</div>';
489
- $('#toy-logs').innerHTML = (t.logs || []).length
490
- ? t.logs.map((n) => `<button class="log-btn" data-toylog="${esc(n)}">${esc(n)}</button>`).join('')
491
- : '<div class="muted">还没有玩具运行日志</div>';
492
- } catch { /* 老版本无 toys 端点时忽略 */ }
493
- }
494
- let lifeLogTimer = null;
495
- let currentLifeLog = null;
496
- async function showLog(name) {
497
- const body = $('#life-log-body');
498
- try {
499
- body.textContent = await (await fetch(`/api/me/roles/${lifeRoleId}/life/log/${encodeURIComponent(name)}`)).text();
500
- body.classList.remove('hidden');
501
- currentLifeLog = name;
502
- startLifeLogPolling();
503
- } catch (err) { status(err.message, true); }
504
- }
505
- function startLifeLogPolling() {
506
- if (lifeLogTimer) return;
507
- lifeLogTimer = setInterval(async () => {
508
- if (!currentLifeLog) return;
509
- try {
510
- const body = $('#life-log-body');
511
- body.textContent = await (await fetch(`/api/me/roles/${lifeRoleId}/life/log/${encodeURIComponent(currentLifeLog)}`)).text();
512
- } catch { /* 单次刷新失败忽略,下一轮再试 */ }
513
- }, 2000);
514
- }
515
- function stopLifeLogPolling() {
516
- if (lifeLogTimer) { clearInterval(lifeLogTimer); lifeLogTimer = null; }
517
- }
518
- $('#life-logs').addEventListener('click', async (e) => {
519
- const btn = e.target.closest('button[data-log]');
520
- if (!btn) return;
521
- await showLog(btn.dataset.log);
522
- });
523
- $('#life-scripts').addEventListener('click', async (e) => {
524
- const btn = e.target.closest('button[data-script]');
525
- if (!btn) return;
526
- const src = $('#life-source');
527
- try {
528
- src.textContent = await (await fetch(`/api/me/roles/${lifeRoleId}/life/script/${encodeURIComponent(btn.dataset.script)}`)).text();
529
- src.classList.remove('hidden');
530
- } catch (err) { status(err.message, true); }
531
- });
532
- $('#life-running').addEventListener('click', async (e) => {
533
- const logBtn = e.target.closest('button.run-log');
534
- if (logBtn) { await showLog(logBtn.dataset.log); return; }
620
+ const t = await api(`/api/me/roles/${lifeRoleId}/toys`);
621
+ $('#toy-running-count').textContent = `${(t.running || []).length} 个运行中`;
622
+ $('#toy-running').innerHTML = (t.running || []).length
623
+ ? 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>${r.logName ? `<button class="ghost toy-run-log" data-toylog="${esc(r.logName)}">日志</button>` : ''}<button class="ghost danger toy-stop" data-run="${esc(r.runId)}">终止</button></div>`).join('')
624
+ : '<div class="muted">没有玩具脚本在运行(dsh 用 toy_run_script 运行)</div>';
625
+ $('#toy-script-count').textContent = (t.scripts || []).length;
626
+ $('#toy-scripts').innerHTML = (t.scripts || []).length
627
+ ? t.scripts.map((n) => resourceButton('toy', 'source', n, 'data-toyscript')).join('')
628
+ : '<div class="muted">toys/ 下还没有脚本</div>';
629
+ $('#toy-log-count').textContent = (t.logs || []).length;
630
+ $('#toy-logs').innerHTML = (t.logs || []).length
631
+ ? t.logs.map((n) => resourceButton('toy', 'log', n, 'data-toylog')).join('')
632
+ : '<div class="muted">还没有玩具运行日志</div>';
633
+ } catch { /* 老版本无 toys 端点时忽略 */ }
634
+ }
635
+ document.querySelectorAll('[data-script-space]').forEach((button) => button.addEventListener('click', async () => {
636
+ const group = button.dataset.scriptSpace;
637
+ selectScriptSpace(group);
638
+ await showFirstLog(group);
639
+ const selected = scriptSelection[group];
640
+ currentScriptLog = selected.kind === 'log' ? { group, name: selected.name } : null;
641
+ }));
642
+ document.querySelectorAll('[data-asset-kind]').forEach((button) => button.addEventListener('click', () => selectAssetKind(button.dataset.assetGroup, button.dataset.assetKind)));
643
+ $('#life-logs').addEventListener('click', async (e) => {
644
+ const btn = e.target.closest('button[data-log]');
645
+ if (!btn) return;
646
+ await showScriptLog('life', btn.dataset.log);
647
+ });
648
+ $('#life-scripts').addEventListener('click', async (e) => {
649
+ const btn = e.target.closest('button[data-script]');
650
+ if (!btn) return;
651
+ await showScriptSource('life', btn.dataset.script);
652
+ });
653
+ $('#life-running').addEventListener('click', async (e) => {
654
+ const logBtn = e.target.closest('button.run-log');
655
+ if (logBtn) { await showScriptLog('life', logBtn.dataset.log); return; }
535
656
  const btn = e.target.closest('button[data-run]');
536
657
  if (!btn) return;
537
658
  try {
@@ -540,8 +661,10 @@ $('#life-running').addEventListener('click', async (e) => {
540
661
  await refreshLife();
541
662
  } catch (err) { status(err.message, true); }
542
663
  });
543
- $('#toy-running').addEventListener('click', async (e) => {
544
- const btn = e.target.closest('button.toy-stop');
664
+ $('#toy-running').addEventListener('click', async (e) => {
665
+ const logBtn = e.target.closest('button.toy-run-log');
666
+ if (logBtn) { await showScriptLog('toy', logBtn.dataset.toylog); return; }
667
+ const btn = e.target.closest('button.toy-stop');
545
668
  if (!btn) return;
546
669
  try {
547
670
  const r = await api(`/api/me/roles/${lifeRoleId}/toys/stop`, 'POST', { runId: btn.dataset.run });
@@ -549,27 +672,17 @@ $('#toy-running').addEventListener('click', async (e) => {
549
672
  await refreshLife();
550
673
  } catch (err) { status(err.message, true); }
551
674
  });
552
- $('#toy-logs').addEventListener('click', async (e) => {
553
- const btn = e.target.closest('button[data-toylog]');
554
- if (!btn) return;
555
- try {
556
- const txt = await (await fetch(`/api/me/roles/${lifeRoleId}/toys/log/${encodeURIComponent(btn.dataset.toylog)}`)).text();
557
- $('#toy-source').classList.add('hidden');
558
- $('#toy-log-body').textContent = txt;
559
- $('#toy-log-body').classList.remove('hidden');
560
- } catch (err) { status(err.message, true); }
561
- });
562
- $('#toy-scripts').addEventListener('click', async (e) => {
563
- const btn = e.target.closest('button[data-toyscript]');
564
- if (!btn) return;
565
- try {
566
- const txt = await (await fetch(`/api/me/roles/${lifeRoleId}/toys/script/${encodeURIComponent(btn.dataset.toyscript)}`)).text();
567
- $('#toy-log-body').classList.add('hidden');
568
- $('#toy-source').textContent = txt;
569
- $('#toy-source').classList.remove('hidden');
570
- } catch (err) { status(err.message, true); }
571
- });
572
- $('#btn-close-life').addEventListener('click', () => { stopLifeLogPolling(); stopLifeRefresh(); currentLifeLog = null; showRoles(); });
675
+ $('#toy-logs').addEventListener('click', async (e) => {
676
+ const btn = e.target.closest('button[data-toylog]');
677
+ if (!btn) return;
678
+ await showScriptLog('toy', btn.dataset.toylog);
679
+ });
680
+ $('#toy-scripts').addEventListener('click', async (e) => {
681
+ const btn = e.target.closest('button[data-toyscript]');
682
+ if (!btn) return;
683
+ await showScriptSource('toy', btn.dataset.toyscript);
684
+ });
685
+ $('#btn-close-life').addEventListener('click', () => { stopScriptLogPolling(); stopLifeRefresh(); showRoles(); });
573
686
 
574
687
  /* ------------------------------- 表情包管理 ------------------------------- */
575
688
  async function openMemes(rid) {
@@ -57,30 +57,31 @@
57
57
  <section id="editor-view" class="workspace-view editor-view hidden">
58
58
  <div class="view-header"><div><p class="eyebrow">CHARACTER EDITOR</p><h2 id="editor-title">新建角色</h2><p>先定义角色,再配置她/他的连接与主动节奏。</p></div><button id="btn-close-editor" class="icon-button" type="button" aria-label="关闭编辑器">×</button></div>
59
59
  <form id="role-form" class="editor-form">
60
- <section class="editor-section"><div class="section-heading"><span>01</span><div><h3>角色设定</h3><p>这部分会成为角色理解自己和你的基础。</p></div></div>
60
+ <nav class="editor-nav" aria-label="角色编辑分区"><a href="#editor-persona">角色设定</a><a href="#editor-model">模型与能力</a><a href="#editor-proactive">主动互动</a><a href="#editor-connection">QQ 连接</a><a href="#editor-voice">语音</a></nav>
61
+ <details id="editor-persona" class="editor-section" open><summary class="section-heading"><span>01</span><div><h3>角色设定</h3><p>这部分会成为角色理解自己和你的基础。</p></div></summary>
61
62
  <div class="form-grid compact"><label>角色名<input id="f-name" required placeholder="给 ta 一个名字"></label><label>年龄 <span class="optional">可选</span><input id="f-age" placeholder="例如 24"></label><label class="span-2">头像提示 <span class="optional">可选</span><input id="f-avatar" placeholder="例如:长发、黑猫、月光"></label><label class="span-2">性格<input id="f-personality" placeholder="例如:温柔、机敏、有一点傲娇"></label></div>
62
63
  <div class="form-grid"><label class="span-2">背景故事<textarea id="f-backstory" rows="4" placeholder="ta 从哪里来,正在过怎样的生活?"></textarea></label><label>说话风格<textarea id="f-speaking" rows="4" placeholder="ta 如何说话?"></textarea></label><label>与你的关系<textarea id="f-relationship" rows="4" placeholder="你们是什么关系?"></textarea></label><label class="span-2">日程 <span class="optional">每行一条</span><textarea id="f-schedule" rows="3" placeholder="早安=08:00&#10;晚安=23:00"></textarea></label></div>
63
64
  <div class="device-pick"><div class="field-label">可用设备 <span class="optional">需要先在“我的设备”登记</span></div><div id="f-devices" class="device-checkboxes">加载中…</div></div>
64
- </section>
65
- <section class="editor-section"><div class="section-heading"><span>02</span><div><h3>模型与能力</h3><p>角色只会使用这里为其指定的模型与凭据。</p></div></div>
65
+ </details>
66
+ <details id="editor-model" class="editor-section"><summary class="section-heading"><span>02</span><div><h3>模型与能力</h3><p>角色只会使用这里为其指定的模型与凭据。</p></div></summary>
66
67
  <div class="form-grid"><label>Provider <span class="optional">可选</span><input id="f-provider" placeholder="留空自动注册"></label><label>模型<input id="f-model" placeholder="deepseek-v4-flash"></label><label class="span-2">API 地址 <span class="optional">OpenAI 兼容</span><input id="f-apiurl" placeholder="https://api.deepseek.com/v1"></label><label class="span-2">API Key <span class="optional">仅自定义地址需要</span><input id="f-apikey" type="password" placeholder="sk-…"></label></div>
67
68
  <label class="switch-row"><input type="checkbox" id="f-model-vision"><span class="switch"></span><span><b>支持图片输入</b><small>让导演能够直接理解用户发来的图片。</small></span></label>
68
- </section>
69
- <section class="editor-section"><div class="section-heading"><span>03</span><div><h3>主动互动</h3><p>决定角色何时可以主动联系你。</p></div></div>
69
+ </details>
70
+ <details id="editor-proactive" class="editor-section"><summary class="section-heading"><span>03</span><div><h3>主动互动</h3><p>决定角色何时可以主动联系你。</p></div></summary>
70
71
  <label class="switch-row"><input id="f-proactive-enabled" type="checkbox" checked><span class="switch"></span><span><b>允许主动唤醒</b><small>关闭后,角色只会回应你主动发起的对话。</small></span></label>
71
72
  <div class="form-grid compact"><label>每日主动上限<input id="f-maxwake" type="number" min="0" max="50" value="5"></label><label>沉默归档(分钟)<input id="f-archive" type="number" min="0" value="45"></label><label>晚间问候时刻<input id="f-evening" value="20:00"></label><label>免打扰时段<input id="f-quiet" placeholder="23:00-07:00"></label></div>
72
73
  <label class="switch-row"><input id="f-meme-enabled" type="checkbox"><span class="switch"></span><span><b>周期收集表情包</b><small>导演会用搜索和视觉识别补充角色的表情库。</small></span></label>
73
74
  <div class="form-grid compact"><label>收集周期(天)<input id="f-meme-interval" type="number" min="1" value="7"></label></div>
74
75
  <details class="advanced"><summary>配置表情包视觉 API <span>可选</span></summary><div class="form-grid compact"><label>Provider<input id="f-meme-vision-provider" placeholder="留空自动"></label><label>视觉模型<input id="f-meme-vision-model" placeholder="deepseek-v4-flash-vision-exp"></label><label class="span-2">API 地址<input id="f-meme-vision-apiurl" placeholder="https://…"></label><label class="span-2">API Key<input id="f-meme-vision-apikey" type="password" placeholder="sk-…"></label></div></details>
75
- </section>
76
+ </details>
76
77
  <div class="form-footer"><span id="editor-error" class="form-error"></span><button type="submit" id="role-save" class="button primary">保存角色</button></div>
77
78
  </form>
78
- <form id="bot-form" class="connection-card hidden"><div class="connection-heading"><div><p class="eyebrow">QQ CONNECTION</p><h3>QQ 机器人连接</h3><p id="bot-status-line"></p></div><span class="connection-dot"></span></div>
79
+ <form id="bot-form" class="connection-card hidden"><div id="editor-connection" class="connection-heading"><div><p class="eyebrow">QQ CONNECTION</p><h3>QQ 机器人连接</h3><p id="bot-status-line"></p></div><span class="connection-dot"></span></div>
79
80
  <div class="form-grid compact"><label>AppID<input id="f-appid" placeholder="QQ 开放平台机器人 AppID"></label><label>AppSecret<input id="f-appsecret" type="password" autocomplete="new-password" placeholder="已配置则留空保持不变"></label><label>唤醒撞车窗口(分钟)<input id="f-chatwindow" type="number" min="1" value="5"></label></div>
80
81
  <div class="setting-pills"><label class="check-pill"><input id="f-sandbox" type="checkbox" checked> 沙箱环境</label><label class="check-pill"><input id="f-streaming" type="checkbox"> 流式回复</label></div>
81
82
  <div class="connection-actions"><span id="bot-error" class="form-error"></span><div><button type="button" id="btn-toggle-sleep" class="button secondary hidden"></button><button type="button" id="btn-del-bot" class="button danger hidden">删除连接</button><button type="submit" class="button primary">保存连接</button></div></div>
82
83
  </form>
83
- <form id="voice-form" class="connection-card hidden"><div class="connection-heading"><div><p class="eyebrow">MIMO VOICE</p><h3>MiMo 音色克隆</h3><p id="voice-status-line">配置角色音色与参考音频后,导演可在同一次发送中发语音。</p></div></div>
84
+ <form id="voice-form" class="connection-card hidden"><div id="editor-voice" class="connection-heading"><div><p class="eyebrow">MIMO VOICE</p><h3>MiMo 音色克隆</h3><p id="voice-status-line">配置角色音色与参考音频后,导演可在同一次发送中发语音。</p></div></div>
84
85
  <label class="switch-row"><input id="f-voice-enabled" type="checkbox"><span class="switch"></span><span><b>启用语音消息</b><small>仅在 API Key 和参考音频都配置后可用。</small></span></label>
85
86
  <div class="form-grid compact"><label>MiMo API Key<input id="f-mimo-key" type="password" autocomplete="new-password" placeholder="已配置则留空保持不变"></label><label>模型<input id="f-mimo-model" value="mimo-v2.5-tts-voiceclone"></label><label class="span-2">角色语音设定<textarea id="f-voice-role" rows="3" placeholder="例如:成年男性;中性化、可爱的正太音。"></textarea></label></div>
86
87
  <div class="upload-card"><div><b>参考音频</b><p id="voice-reference-info">支持 WAV / MP3;Base64 编码后不超过 10MB。</p></div><div class="upload-actions"><input id="voice-reference" type="file" accept="audio/wav,audio/x-wav,audio/mpeg,audio/mp3,.wav,.mp3"><button id="btn-voice-reference" class="button secondary" type="button">上传参考音频</button></div></div>
@@ -88,9 +89,60 @@
88
89
  </form>
89
90
  </section>
90
91
 
91
- <section id="life-view" class="workspace-view monitor-view hidden"><div class="view-header"><div><p class="eyebrow">LIFE SCRIPT MONITOR</p><h2><span id="life-role-name"></span> 的生活脚本</h2><p>脚本内容、运行状态与日志均在这里透明可见。</p></div><button id="btn-close-life" class="icon-button" type="button" aria-label="关闭">×</button></div>
92
- <div class="monitor-grid"><section class="monitor-card span-wide"><h3>正在运行</h3><div id="life-running" class="list-surface"></div></section><section class="monitor-card"><h3>脚本文件</h3><div id="life-scripts" class="list-surface"></div></section><section class="monitor-card"><h3>最近日志</h3><div id="life-logs" class="list-surface"></div></section><section class="monitor-card"><h3>快照备份</h3><ul id="life-backups"></ul></section><section class="monitor-card"><h3>玩具脚本</h3><div id="toy-running" class="list-surface"></div><div id="toy-scripts" class="list-surface"></div><div id="toy-logs" class="list-surface"></div></section></div>
93
- <details class="raw-data"><summary>查看运行清单</summary><pre id="life-manifest" class="code"></pre></details><pre id="life-source" class="code hidden"></pre><pre id="life-log-body" class="code hidden"></pre><pre id="toy-log-body" class="code hidden"></pre><pre id="toy-source" class="code hidden"></pre>
92
+ <section id="life-view" class="workspace-view monitor-view hidden">
93
+ <div class="view-header monitor-header"><div><p class="eyebrow">SCRIPT WORKSPACE</p><h2><span id="life-role-name"></span> 的脚本</h2><p>查看运行状态、源码和实时日志,无需离开当前视口。</p></div><button id="btn-close-life" class="icon-button" type="button" aria-label="关闭">×</button></div>
94
+ <div class="script-type-tabs" role="tablist" aria-label="脚本类型">
95
+ <button class="script-type-tab active" type="button" role="tab" aria-selected="true" aria-controls="script-space-life" data-script-space="life"><span>生活脚本</span><b id="life-running-count">0 个运行中</b></button>
96
+ <button class="script-type-tab" type="button" role="tab" aria-selected="false" aria-controls="script-space-toy" data-script-space="toy"><span>玩具脚本</span><b id="toy-running-count">0 个运行中</b></button>
97
+ <span class="monitor-live"><i></i> 每 3 秒自动刷新</span>
98
+ </div>
99
+
100
+ <section id="script-space-life" class="script-space" role="tabpanel">
101
+ <section class="runtime-panel"><div class="panel-title"><div><p class="eyebrow">RUNTIME</p><h3>正在运行</h3></div></div><div id="life-running" class="list-surface runtime-list"></div></section>
102
+ <div class="script-workbench">
103
+ <aside class="asset-panel">
104
+ <div class="asset-tabs" role="tablist" aria-label="生活脚本资源">
105
+ <button class="asset-tab active" type="button" role="tab" aria-selected="true" data-asset-group="life" data-asset-kind="logs">日志 <b id="life-log-count">0</b></button>
106
+ <button class="asset-tab" type="button" role="tab" aria-selected="false" data-asset-group="life" data-asset-kind="scripts">脚本 <b id="life-script-count">0</b></button>
107
+ <button class="asset-tab" type="button" role="tab" aria-selected="false" data-asset-group="life" data-asset-kind="backups">备份 <b id="life-backup-count">0</b></button>
108
+ </div>
109
+ <div class="asset-list-wrap">
110
+ <div id="life-logs" class="list-surface asset-list" data-asset-panel="logs"></div>
111
+ <div id="life-scripts" class="list-surface asset-list hidden" data-asset-panel="scripts"></div>
112
+ <div id="life-backups" class="list-surface asset-list hidden" data-asset-panel="backups"></div>
113
+ </div>
114
+ <details class="raw-data"><summary>运行清单</summary><pre id="life-manifest" class="code"></pre></details>
115
+ </aside>
116
+ <section class="inspector-panel">
117
+ <header class="inspector-header"><div><p id="life-inspector-kind" class="eyebrow">PREVIEW</p><h3 id="life-inspector-title">选择一条日志或脚本</h3></div><span id="life-inspector-state" class="inspector-state">日志打开后自动追踪更新</span></header>
118
+ <div id="life-preview-empty" class="preview-empty"><span>⌁</span><b>内容查看器</b><p>从左侧选择日志、脚本或运行中项目。</p></div>
119
+ <pre id="life-source" class="code inspector-code hidden"></pre>
120
+ <pre id="life-log-body" class="code inspector-code hidden"></pre>
121
+ </section>
122
+ </div>
123
+ </section>
124
+
125
+ <section id="script-space-toy" class="script-space hidden" role="tabpanel">
126
+ <section class="runtime-panel"><div class="panel-title"><div><p class="eyebrow">RUNTIME</p><h3>正在运行</h3></div></div><div id="toy-running" class="list-surface runtime-list"></div></section>
127
+ <div class="script-workbench">
128
+ <aside class="asset-panel">
129
+ <div class="asset-tabs" role="tablist" aria-label="玩具脚本资源">
130
+ <button class="asset-tab active" type="button" role="tab" aria-selected="true" data-asset-group="toy" data-asset-kind="logs">日志 <b id="toy-log-count">0</b></button>
131
+ <button class="asset-tab" type="button" role="tab" aria-selected="false" data-asset-group="toy" data-asset-kind="scripts">脚本 <b id="toy-script-count">0</b></button>
132
+ </div>
133
+ <div class="asset-list-wrap">
134
+ <div id="toy-logs" class="list-surface asset-list" data-asset-panel="logs"></div>
135
+ <div id="toy-scripts" class="list-surface asset-list hidden" data-asset-panel="scripts"></div>
136
+ </div>
137
+ </aside>
138
+ <section class="inspector-panel">
139
+ <header class="inspector-header"><div><p id="toy-inspector-kind" class="eyebrow">PREVIEW</p><h3 id="toy-inspector-title">选择一条日志或脚本</h3></div><span id="toy-inspector-state" class="inspector-state">日志打开后自动追踪更新</span></header>
140
+ <div id="toy-preview-empty" class="preview-empty"><span>⌁</span><b>内容查看器</b><p>从左侧选择日志、脚本或运行中项目。</p></div>
141
+ <pre id="toy-log-body" class="code inspector-code hidden"></pre>
142
+ <pre id="toy-source" class="code inspector-code hidden"></pre>
143
+ </section>
144
+ </div>
145
+ </section>
94
146
  </section>
95
147
 
96
148
  <section id="meme-view" class="workspace-view meme-view hidden"><div class="view-header"><div><p class="eyebrow">REACTION LIBRARY</p><h2><span id="meme-role-name"></span> 的表情包</h2><p>管理角色可以理解、选择并发送的反应图。</p></div><button id="btn-close-meme" class="icon-button" type="button" aria-label="关闭">×</button></div>
@@ -1 +1,8 @@
1
1
  :root{--ink:#23242b;--muted:#73757f;--line:#e8e8ed;--paper:#fff;--wash:#f7f7f8;--dark:#25252f;--violet:#6d5ce7;--violet-dark:#5544d5;--violet-pale:#f0efff;--green:#26734d;--red:#c64c56;--amber:#9b6b1e;--radius:16px;--shadow:0 10px 30px #2826370b}*{box-sizing:border-box}body{margin:0;background:var(--wash);color:var(--ink);font:14px/1.55 Inter,ui-sans-serif,system-ui,"Microsoft YaHei",sans-serif}.hidden{display:none!important}.site-shell{min-height:100vh}.button{border:1px solid transparent;border-radius:10px;cursor:pointer;font:inherit;font-weight:650;padding:10px 15px;transition:.18s ease}.button:hover{transform:translateY(-1px)}.button.primary{background:var(--violet);color:#fff;box-shadow:0 6px 14px #6d5ce735}.button.primary:hover{background:var(--violet-dark)}.button.secondary{background:#fff;border-color:var(--line);color:var(--ink)}.button.danger{background:#fff2f3;border-color:#f3dadd;color:var(--red)}.wide{width:100%}.eyebrow{color:var(--violet);font-size:10px;font-weight:800;letter-spacing:.14em;margin:0 0 6px}.optional{color:#999ba5;font-size:12px;font-weight:400}.muted{color:var(--muted)}.form-error{color:var(--red);font-size:13px}.text-button{background:none;border:0;color:var(--violet);cursor:pointer;font:inherit;font-weight:650;padding:8px 0}.auth-screen{align-items:center;background:var(--dark);display:grid;grid-template-columns:minmax(300px,1fr) minmax(360px,520px);justify-content:center;min-height:100vh;overflow:hidden;padding:40px}.auth-card{background:#fff;border-radius:24px;box-shadow:0 30px 60px #0003;justify-self:center;padding:42px;position:relative;width:min(100%,440px);z-index:1}.auth-art{height:100%;min-height:540px;position:relative}.auth-art:before,.auth-art:after,.auth-art span{border:1px solid #ffffff1d;border-radius:999px;content:"";left:50%;position:absolute;top:50%;transform:translate(-50%,-50%)}.auth-art:before{height:460px;width:460px}.auth-art:after{height:300px;width:300px}.auth-art span:first-child{background:#7869ee;height:110px;width:110px;box-shadow:0 0 0 26px #7869ee25,0 0 60px #7869ee}.auth-art span:nth-child(2){background:#edb45c;border:0;height:12px;left:20%;top:23%;width:12px}.auth-art span:nth-child(3){background:#a4e3c2;border:0;height:16px;left:70%;top:74%;width:16px}.brand{align-items:center;color:var(--ink);display:inline-flex;font-size:17px;font-weight:760;gap:9px;letter-spacing:-.03em;text-decoration:none}.brand i{align-items:center;background:var(--violet);border-radius:9px;color:white;display:inline-flex;font:700 19px Georgia,serif;height:29px;justify-content:center;width:29px}.brand-large{margin-bottom:48px}.auth-copy h1{font-size:31px;letter-spacing:-.055em;line-height:1.15;margin:0 0 13px}.auth-copy>p:last-child{color:var(--muted);margin:0 0 30px}.form-stack{display:grid;gap:15px}.form-stack label,.form-grid label,.inline-entry label{color:#555762;display:grid;font-size:12px;font-weight:650;gap:6px}input,textarea{background:#fff;border:1px solid #dedee5;border-radius:9px;color:var(--ink);font:inherit;font-weight:400;outline:none;padding:10px 11px;transition:border .15s,box-shadow .15s;width:100%}input:focus,textarea:focus{border-color:var(--violet);box-shadow:0 0 0 3px #6d5ce71a}textarea{resize:vertical}.auth-card .form-error{margin:10px 0 0;min-height:19px}.app-shell{display:grid;grid-template-columns:230px minmax(0,1fr);min-height:100vh}.sidebar{background:var(--dark);color:#d8d8df;display:flex;flex-direction:column;padding:26px 16px}.sidebar .brand{color:#fff;padding:0 10px}.side-nav{display:grid;gap:5px;margin-top:48px}.nav-item{align-items:center;background:none;border:0;border-radius:9px;color:#b8b8c3;cursor:pointer;display:flex;font:inherit;font-weight:600;gap:10px;padding:11px 12px;text-align:left;width:100%}.nav-item b{color:#a29be9;font-size:16px;font-weight:400;width:18px}.nav-item:hover,.nav-item.active{background:#ffffff12;color:#fff}.nav-item.active{box-shadow:inset 2px 0 var(--violet)}.sidebar-foot{border-top:1px solid #ffffff16;display:grid;gap:5px;margin-top:auto;padding-top:16px}.nav-item.subdued{color:#898994}.app-main{margin:0 auto;max-width:1240px;padding:36px 46px 80px;width:100%}.app-header{align-items:center;display:flex;justify-content:space-between;margin:0 0 36px}.app-header h1{font-size:26px;letter-spacing:-.045em;line-height:1.1;margin:0}.account-chip{align-items:center;color:var(--muted);display:flex;font-size:13px;font-weight:650;gap:9px}.account-avatar{align-items:center;background:var(--violet-pale);border-radius:50%;color:var(--violet);display:inline-flex;font-size:13px;height:32px;justify-content:center;width:32px}.toast{background:#272632;border-radius:11px;box-shadow:var(--shadow);color:white;left:50%;padding:10px 15px;position:fixed;top:20px;transform:translateX(-50%);z-index:10}.toast.error{background:#ae3f4a}.workspace-view{animation:appear .2s ease}@keyframes appear{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}.intro-row,.view-header{align-items:flex-start;display:flex;gap:20px;justify-content:space-between;margin-bottom:22px}.intro-row h2,.view-header h2{font-size:21px;letter-spacing:-.035em;margin:0}.intro-row p,.view-header p{color:var(--muted);margin:5px 0 0}.role-grid{display:grid;gap:14px;grid-template-columns:repeat(auto-fill,minmax(310px,1fr))}.role-card{background:var(--paper);border:1px solid var(--line);border-radius:var(--radius);box-shadow:var(--shadow);display:flex;flex-direction:column;min-height:210px;padding:20px}.role-main{display:grid;gap:7px}.role-main strong{font-size:18px;letter-spacing:-.025em}.role-main .row:first-child{align-items:center}.row{align-items:center;display:flex;flex-wrap:wrap;gap:7px}.role-card .muted{font-size:13px}.role-actions{border-top:1px solid var(--line);gap:6px;margin-top:auto;padding-top:15px}.role-actions button{background:none;border:0;color:#555660;cursor:pointer;font:inherit;font-size:13px;font-weight:650;padding:6px}.role-actions button:hover{color:var(--violet)}.role-actions button.danger{color:var(--red)}.tag{background:#f5f5f7;border:1px solid #e5e5e9;border-radius:999px;color:#777884;font-size:11px;font-weight:650;padding:2px 8px}.tag.ok{background:#ebf8f0;border-color:#c8e9d4;color:var(--green)}.tag.sleeping{background:#fff6e6;border-color:#f1d9a9;color:var(--amber)}.quiet-note{align-items:flex-start;border-top:1px solid var(--line);color:var(--muted);display:flex;font-size:12px;gap:14px;margin-top:28px;padding:17px 2px}.quiet-note b{color:#4d4e57;white-space:nowrap}.panel-view,.editor-view,.monitor-view,.meme-view{background:var(--paper);border:1px solid var(--line);border-radius:20px;box-shadow:var(--shadow);padding:28px}.icon-button{align-items:center;background:#f5f5f7;border:0;border-radius:50%;color:#6c6c75;cursor:pointer;display:inline-flex;font-size:24px;height:34px;justify-content:center;line-height:1;width:34px}.info-callout{background:var(--violet-pale);border-radius:11px;color:#555275;font-size:13px;margin-bottom:20px;padding:13px 15px}.inline-entry{align-items:end;display:flex;gap:12px;margin-bottom:20px;max-width:520px}.inline-entry label{flex:1}.list-surface{display:grid;gap:7px}.list-surface:empty:after{color:var(--muted);content:"暂无内容"}.editor-view{padding:0;overflow:hidden}.editor-view>.view-header{background:#fbfbfc;border-bottom:1px solid var(--line);margin:0;padding:28px}.editor-form{padding:0 28px}.editor-section{border-bottom:1px solid var(--line);padding:30px 0}.section-heading{align-items:flex-start;display:flex;gap:14px;margin-bottom:22px}.section-heading>span{align-items:center;background:var(--violet-pale);border-radius:50%;color:var(--violet);display:flex;font-size:11px;font-weight:800;height:28px;justify-content:center;width:28px}.section-heading h3,.connection-heading h3{font-size:16px;letter-spacing:-.02em;margin:0}.section-heading p{color:var(--muted);font-size:13px;margin:3px 0 0}.form-grid{display:grid;gap:15px;grid-template-columns:repeat(2,minmax(0,1fr))}.form-grid.compact{gap:12px}.span-2{grid-column:span 2}.device-pick{background:#fafafd;border:1px solid var(--line);border-radius:11px;margin-top:15px;padding:13px}.field-label{font-size:12px;font-weight:650;margin-bottom:8px}.device-checkboxes{color:var(--muted);display:flex;flex-wrap:wrap;gap:8px 18px;font-size:13px}.device-checkboxes label{align-items:center;display:flex;gap:6px}.device-checkboxes input{width:auto}.switch-row{align-items:center;background:#fafafd;border:1px solid var(--line);border-radius:11px;cursor:pointer;display:flex;gap:10px;margin-top:15px;padding:11px 13px}.switch-row input{height:1px;opacity:0;position:absolute;width:1px}.switch{background:#d4d5dc;border-radius:99px;display:inline-block;flex:none;height:22px;position:relative;width:38px}.switch:after{background:white;border-radius:50%;box-shadow:0 1px 3px #0003;content:"";height:16px;left:3px;position:absolute;top:3px;transition:.18s;width:16px}.switch-row input:checked+.switch{background:var(--violet)}.switch-row input:checked+.switch:after{transform:translateX(16px)}.switch-row b,.switch-row small{display:block}.switch-row small{color:var(--muted);font-size:12px;margin-top:1px}.advanced{border:1px solid var(--line);border-radius:10px;color:#5d5d68;margin-top:15px;padding:0 13px}.advanced summary{cursor:pointer;font-weight:650;padding:12px 0}.advanced summary span{color:var(--muted);font-size:12px;font-weight:400}.advanced[open]{padding-bottom:14px}.form-footer{align-items:center;display:flex;justify-content:space-between;padding:22px 0}.connection-card{background:#272631;color:white;margin-top:22px;padding:27px 28px}.connection-heading{align-items:flex-start;display:flex;justify-content:space-between;margin-bottom:20px}.connection-heading .eyebrow{color:#aaa2ff}.connection-heading p:last-child{color:#c5c5cd;font-size:13px;margin:5px 0 0}.connection-dot{background:#6fe09e;border-radius:50%;box-shadow:0 0 0 5px #6fe09e1f;height:8px;margin:7px;width:8px}.connection-card input{background:#ffffff0c;border-color:#ffffff25;color:white}.connection-card .form-grid label{color:#dad9e0}.setting-pills{display:flex;gap:8px;margin-top:15px}.check-pill{background:#ffffff12;border:1px solid #ffffff1a;border-radius:99px;color:#dfdfe7;font-size:12px;padding:7px 10px}.check-pill input{margin-right:5px;width:auto}.connection-actions{align-items:center;display:flex;justify-content:space-between;margin-top:20px}.connection-actions>div{display:flex;gap:8px}.connection-actions .secondary{background:#ffffff10;border-color:#ffffff25;color:white}.monitor-grid{display:grid;gap:14px;grid-template-columns:repeat(2,minmax(0,1fr))}.monitor-card{background:#fafafd;border:1px solid var(--line);border-radius:12px;padding:16px}.monitor-card h3{font-size:13px;margin:0 0 12px}.span-wide{grid-column:span 2}.log-btn{background:white;border:1px solid var(--line);border-radius:8px;color:#4a4b55;cursor:pointer;font:12px ui-monospace,monospace;padding:8px;text-align:left}.run-row{align-items:center;background:white;border:1px solid var(--line);border-radius:9px;display:flex;gap:8px;justify-content:space-between;padding:8px}.run-info{font:12px ui-monospace,monospace}.run-row .ghost,.meme-card .ghost{background:white;border:1px solid var(--line);border-radius:7px;color:#50515a;cursor:pointer;font:inherit;padding:5px 8px}.run-row .danger,.meme-card .danger{color:var(--red)}.raw-data{margin-top:16px}.raw-data summary{color:var(--muted);cursor:pointer;font-size:13px}.code{background:#1f2029;border-radius:10px;color:#e9e9ee;font:12px/1.55 ui-monospace,Consolas,monospace;margin:12px 0;max-height:340px;overflow:auto;padding:15px;white-space:pre-wrap;word-break:break-all}.upload-card{align-items:center;background:#fafafd;border:1px dashed #cfcfda;border-radius:13px;display:flex;flex-wrap:wrap;gap:15px;justify-content:space-between;margin-bottom:22px;padding:18px}.upload-card b{font-size:14px}.upload-card p{color:var(--muted);font-size:12px;margin:3px 0 0}.upload-actions{align-items:center;display:flex;gap:8px}.upload-actions input{font-size:12px;max-width:220px}.meme-grid{display:grid;gap:14px;grid-template-columns:repeat(auto-fill,minmax(190px,1fr))}.meme-card{background:#fafafd;border:1px solid var(--line);border-radius:12px;overflow:hidden}.meme-card img{aspect-ratio:1;display:block;object-fit:cover;width:100%}.meme-meta{display:grid;gap:8px;padding:10px}.meme-meta label{color:var(--muted);display:grid;font-size:11px;gap:3px}.meme-meta input{font-size:12px;padding:6px 7px}@media(max-width:820px){.app-shell{display:block}.sidebar{align-items:center;flex-direction:row;gap:15px;padding:12px 15px;position:sticky;top:0;z-index:5}.side-nav{display:flex;margin:0}.sidebar-foot{border:0;display:flex;margin:0 0 0 auto;padding:0}.sidebar-foot .nav-item{font-size:0;padding:8px}.sidebar-foot .nav-item b{font-size:16px}.app-main{padding:28px 20px 60px}.app-header{margin-bottom:26px}.role-grid{grid-template-columns:1fr}.auth-screen{grid-template-columns:1fr;padding:24px}.auth-art{display:none}.auth-card{padding:32px}.brand-large{margin-bottom:35px}}@media(max-width:560px){.sidebar .brand span{display:none}.nav-item{font-size:12px;padding:8px}.side-nav{margin-right:auto}.app-header{align-items:flex-start;gap:12px}.account-chip span:last-child{display:none}.intro-row,.view-header{gap:12px}.intro-row{align-items:flex-end}.form-grid,.monitor-grid{grid-template-columns:1fr}.span-2,.span-wide{grid-column:auto}.editor-view>.view-header,.editor-form{padding-left:18px;padding-right:18px}.connection-card{padding:22px 18px}.connection-actions{align-items:flex-start;flex-direction:column}.upload-card{align-items:flex-start;flex-direction:column}.upload-actions{align-items:flex-start;flex-direction:column;width:100%}.upload-actions input{max-width:none}.quiet-note{flex-direction:column;gap:4px}}
2
+ /* 编辑页按需展开,脚本监管按脚本类型分区。 */
3
+ .editor-nav{background:#fbfbfc;border-bottom:1px solid var(--line);display:flex;gap:6px;margin:0 -28px;padding:11px 28px;position:sticky;top:0;z-index:2}.editor-nav a{border-radius:7px;color:var(--muted);font-size:12px;font-weight:650;padding:5px 8px;text-decoration:none}.editor-nav a:hover{background:var(--violet-pale);color:var(--violet)}.editor-section{padding:0!important}.editor-section[open]{padding-bottom:30px!important}.section-heading{cursor:pointer;margin:0!important;padding:24px 0}.section-heading::-webkit-details-marker{display:none}.section-heading::marker{content:""}.script-monitor{border-top:1px solid var(--line);margin-top:26px;padding-top:24px}.script-monitor:first-of-type{border-top:0;margin-top:0;padding-top:0}.script-monitor-heading{margin-bottom:14px}.script-monitor-heading .eyebrow{margin-bottom:3px}.script-monitor-heading h3{font-size:17px;margin:0}@media(max-width:560px){.editor-nav{margin-left:-18px;margin-right:-18px;overflow:auto;padding-left:18px;padding-right:18px;white-space:nowrap}}
4
+
5
+ /* 脚本工作台 */
6
+ .monitor-view{overflow:hidden;padding:0}.monitor-header{background:#fbfbfc;border-bottom:1px solid var(--line);margin:0;padding:22px 26px}.monitor-header p:last-child{font-size:13px}.script-type-tabs{align-items:center;border-bottom:1px solid var(--line);display:flex;gap:4px;padding:10px 18px}.script-type-tab{align-items:center;background:transparent;border:0;border-radius:10px;color:#656772;cursor:pointer;display:flex;font:inherit;font-weight:700;gap:9px;padding:9px 12px}.script-type-tab:hover{background:#f5f5f8;color:var(--ink)}.script-type-tab.active{background:var(--violet-pale);color:var(--violet)}.script-type-tab b{background:#ededf2;border-radius:999px;color:#858691;font-size:10px;font-weight:700;padding:2px 7px}.script-type-tab.active b{background:#fff;color:var(--violet)}.monitor-live{align-items:center;color:var(--muted);display:flex;font-size:11px;gap:6px;margin-left:auto;padding:0 8px}.monitor-live i{background:#45ad74;border-radius:50%;box-shadow:0 0 0 4px #45ad7418;height:6px;width:6px}.script-space{padding:16px 18px 18px}.runtime-panel{background:#fafafd;border:1px solid var(--line);border-radius:12px;margin-bottom:12px;padding:12px}.panel-title{align-items:center;display:flex;justify-content:space-between;margin-bottom:8px}.panel-title .eyebrow{margin:0}.panel-title h3{font-size:13px;margin:0}.runtime-list{max-height:126px;overflow:auto}.script-workbench{border:1px solid var(--line);border-radius:13px;display:grid;grid-template-columns:minmax(250px,310px) minmax(0,1fr);height:clamp(480px,calc(100vh - 390px),680px);min-height:0;overflow:hidden}.asset-panel{background:#fafafd;border-right:1px solid var(--line);display:flex;flex-direction:column;min-height:0;min-width:0}.asset-tabs{border-bottom:1px solid var(--line);display:flex;padding:8px 8px 0}.asset-tab{background:transparent;border:0;border-bottom:2px solid transparent;color:var(--muted);cursor:pointer;font:inherit;font-size:12px;font-weight:700;padding:8px 9px}.asset-tab:hover{color:var(--ink)}.asset-tab.active{border-bottom-color:var(--violet);color:var(--violet)}.asset-tab b{background:#e9e9ee;border-radius:999px;font-size:10px;margin-left:3px;padding:1px 6px}.asset-list-wrap{flex:1;min-height:0;overflow:auto;padding:10px}.asset-list{align-content:start}.asset-list .muted{font-size:12px;padding:8px}.log-btn{align-items:center;display:flex;min-height:36px;overflow:hidden;position:relative;width:100%}.log-btn:hover{border-color:#cbc8e9;background:#f9f8ff}.log-btn.active{background:var(--violet-pale);border-color:#cdc7ff;color:var(--violet);font-weight:700}.log-btn .item-name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.raw-data{border-top:1px solid var(--line);margin:0;padding:9px 12px}.raw-data summary{font-size:11px}.raw-data .code{max-height:240px}.inspector-panel{background:#1f2029;display:flex;flex-direction:column;min-height:0;min-width:0}.inspector-header{align-items:center;background:#292a35;border-bottom:1px solid #ffffff12;color:#fff;display:flex;justify-content:space-between;min-height:62px;padding:11px 16px}.inspector-header .eyebrow{color:#aaa2ff;margin:0}.inspector-header h3{font-size:13px;font-weight:650;margin:2px 0 0;max-width:48vw;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.inspector-state{color:#9798a5;font-size:10px;white-space:nowrap}.preview-empty{align-items:center;color:#777986;display:flex;flex:1;flex-direction:column;justify-content:center;text-align:center}.preview-empty span{color:#8277df;font:40px Georgia,serif}.preview-empty b{color:#d2d2d8;font-size:13px;margin-top:4px}.preview-empty p{font-size:11px;margin:4px 0}.inspector-code{border-radius:0;flex:1;margin:0;max-height:none;min-height:0;padding:16px 18px;white-space:pre;word-break:normal}.run-row{min-width:0}.run-info{flex:1;min-width:140px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.runtime-list>.muted{font-size:12px;padding:4px}.backup-item{background:#fff;border:1px solid var(--line);border-radius:8px;color:#5d5f69;font:11px ui-monospace,monospace;overflow:hidden;padding:8px;text-overflow:ellipsis;white-space:nowrap}
7
+ @media(max-width:900px){.script-workbench{grid-template-columns:minmax(220px,270px) minmax(0,1fr)}.inspector-state{display:none}}
8
+ @media(max-width:700px){.monitor-header{padding:18px}.monitor-header p:last-child{display:none}.script-type-tabs{overflow:auto;padding:8px 12px;white-space:nowrap}.monitor-live{display:none}.script-space{padding:12px}.runtime-list{max-height:150px}.script-workbench{display:flex;height:auto;min-height:0;overflow:visible;flex-direction:column}.asset-panel{border-bottom:1px solid var(--line);border-right:0;height:270px}.inspector-panel{height:430px}.inspector-header h3{max-width:70vw}.asset-tab{flex:1}.run-row{align-items:flex-start;flex-wrap:wrap}.run-info{flex-basis:100%;white-space:normal}.monitor-view{border-radius:14px}}
package/src/web-server.js CHANGED
@@ -203,10 +203,16 @@ export function createWebServer(deps) {
203
203
  if (!role) return null;
204
204
  const toysDir = join(role.workspace, 'toys');
205
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 }));
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) => ({
210
+ runId: r.runId,
211
+ scriptName: r.scriptName,
212
+ pid: r.pid,
213
+ startedAt: r.startedAt,
214
+ logName: `${r.scriptName.replace(/\.[^.]+$/, '')}-${r.startedAt}.log`,
215
+ }));
210
216
  return { scripts, logs: logs.slice(0, 50), running };
211
217
  }
212
218
  /** 安全化角色 id 参数(防路径穿越)。 */
@@ -214,10 +220,12 @@ export function createWebServer(deps) {
214
220
  const rid = String(raw ?? '');
215
221
  return /^[A-Za-z0-9._-]+$/.test(rid) ? rid : null;
216
222
  }
217
- function logFileNameParam(raw) {
218
- const n = String(raw ?? '');
219
- return /^[\w.-]+\.log$/.test(n) && n !== '..' && !n.includes('/') && !n.includes('\\') ? n : null;
220
- }
223
+ function logFileNameParam(raw) {
224
+ const n = String(raw ?? '');
225
+ // 日志以“脚本名-时间戳.log”命名;脚本名允许中文,故不能只接受 ASCII \w。
226
+ // 仍拒绝路径分隔、控制字符和 Windows 非法文件名字符,防止路径穿越。
227
+ return /^[^/\\\x00-\x1f<>:"|?*]+\.log$/.test(n) && n !== '..' ? n : null;
228
+ }
221
229
  function scriptFileNameParam(raw) {
222
230
  const n = String(raw ?? '');
223
231
  // 排除法:允许中文等任意文件名,只禁路径分隔与 Windows 非法字符(防穿越)
@@ -14,29 +14,20 @@
14
14
  // 若脚本想主动停设备,就在结束前调 toy.stop()。也可被 toy_run_script stop / toy_control stop 中途接管。
15
15
  // 把本文件另存为 workspace/toys/ 下的新文件(勿覆盖已存在的),再用 toy_run_script 运行。
16
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
- ];
17
+ // 脚本应构建玩具运动的波形,而不是随机抽取参数,或将固定参数和固定时长简单串接。
18
+ // 下面只示范连续变化与脚本内 wake 的接口位置;实际波形由导演自行创作。
19
+ const clamp = (value, low, high) => Math.max(low, Math.min(high, value));
20
+ const startedAt = Date.now();
21
+ let woke = false;
35
22
 
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);
23
+ while (Date.now() - startedAt < 90_000) {
24
+ const seconds = (Date.now() - startedAt) / 1000;
25
+ const intensity = Math.round(clamp(65 + 20 * Math.sin(seconds * 0.7), 0, 100));
26
+ const stroke = Math.sin(seconds * 0.7) >= 0 ? '0,66' : '0,100';
27
+ await toy.set({ intensity, stroke });
28
+ if (!woke && seconds >= 35) {
29
+ woke = true;
30
+ await toy.wake({ reason: '脚本中的玩具运动产生了值得导演感知的变化' });
31
+ }
32
+ await toy.sleep(700);
42
33
  }