pygmalion 0.1.15 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +141 -70
  3. package/THIRD_PARTY.md +9 -0
  4. package/docs/ARCHITECTURE.md +66 -108
  5. package/docs/DEPLOY.md +33 -137
  6. package/docs/DEVELOPMENT.md +63 -0
  7. package/docs/DEVICE.md +56 -47
  8. package/docs/EXTENSIONS.md +176 -0
  9. package/docs/PRESET.md +21 -63
  10. package/docs/UPGRADE-0.2.md +52 -0
  11. package/package.json +52 -33
  12. package/preset/pygmalion-director/cordis.patch.yml +234 -0
  13. package/preset/pygmalion-director/pygmalion-tools.js +43 -41
  14. package/scripts/start-local-test.mjs +45 -45
  15. package/skills/pygmalion-life-scripts/SKILL.md +12 -0
  16. package/skills/pygmalion-meme-maintenance/SKILL.md +12 -0
  17. package/skills/pygmalion-memory-archive/SKILL.md +24 -0
  18. package/skills/pygmalion-toy-control/SKILL.md +16 -0
  19. package/src/agent-life.js +608 -606
  20. package/src/archive-tools.js +9 -0
  21. package/src/bot-factory.js +129 -311
  22. package/src/bots.js +264 -275
  23. package/src/channel-qq.js +262 -0
  24. package/src/config.js +69 -68
  25. package/src/delivery-receipt.js +36 -0
  26. package/src/delivery-scope.js +20 -0
  27. package/src/devices/manager.mjs +80 -570
  28. package/src/devices/monsterparty-controller.mjs +393 -0
  29. package/src/devices/{doc.mjs → monsterparty-doc.mjs} +60 -71
  30. package/src/devices/monsterparty.mjs +294 -294
  31. package/src/devices/pb.mjs +110 -110
  32. package/src/devices/registry.mjs +19 -0
  33. package/src/devices/script-helper.mjs +45 -0
  34. package/src/devices/scripts.mjs +109 -0
  35. package/src/devices/service.mjs +254 -0
  36. package/src/director-messages.js +35 -0
  37. package/src/dsh-runtime.js +17 -0
  38. package/src/extension-config.js +20 -0
  39. package/src/extensions.js +118 -0
  40. package/src/heartbeat.js +118 -97
  41. package/src/http-api.js +519 -509
  42. package/src/inbound.js +36 -207
  43. package/src/index.js +109 -37
  44. package/src/llm-provider.js +214 -171
  45. package/src/meme-worker.js +35 -39
  46. package/src/memebox.js +1 -1
  47. package/src/memory-recall.js +55 -0
  48. package/src/memory-write.js +136 -133
  49. package/src/peer-identity.js +26 -0
  50. package/src/persona.js +132 -69
  51. package/src/role-agent.js +155 -0
  52. package/src/role-runtime.js +65 -0
  53. package/src/roleplay-config.js +37 -0
  54. package/src/roleplay-format.js +37 -0
  55. package/src/roleplay-generation.js +36 -0
  56. package/src/roleplay-materials.js +113 -0
  57. package/src/roleplay-output.js +19 -0
  58. package/src/roleplay-parallel.js +239 -0
  59. package/src/roleplay-session.js +128 -0
  60. package/src/roleplay-worker.js +10 -0
  61. package/src/session-log.js +180 -172
  62. package/src/setup-agent.js +92 -100
  63. package/src/skills.js +97 -0
  64. package/src/slash-commands.js +155 -142
  65. package/src/speech-input.js +20 -0
  66. package/src/threads.js +2 -1
  67. package/src/tools.js +226 -254
  68. package/src/voice-defaults.js +13 -0
  69. package/src/voice-mimo.js +139 -125
  70. package/src/voice.js +200 -0
  71. package/src/wakeup.js +85 -66
  72. package/src/web-public/app.js +542 -382
  73. package/src/web-public/index.html +161 -158
  74. package/src/web-public/layout.css +7 -7
  75. package/src/web-public/style.css +12 -8
  76. package/src/web-server.js +161 -102
  77. package/src/worker-tools.js +18 -0
  78. package/templates/sample-life.mjs +59 -59
  79. package/templates/sample-toy.mjs +33 -33
  80. package/preset/pygmalion-director/agent.cordis.yml +0 -262
  81. package/preset/pygmalion-director/preset.yml +0 -3
  82. package/src/message-review.js +0 -276
@@ -1,14 +1,24 @@
1
1
  /* Pygmalion 管理台前端:登录 → 角色列表 → 编辑 / 脚本监管。 */
2
2
  const $ = (sel) => document.querySelector(sel);
3
+ let helpSequence = 0;
4
+ function fieldHelp(label, text) {
5
+ if (!label || !text || label.querySelector('.field-help')) return;
6
+ label.classList.add('has-help');
7
+ const help = document.createElement('details'); help.className = 'field-help';
8
+ const summary = document.createElement('summary'); summary.textContent = '?'; summary.setAttribute('aria-label', '查看此项说明');
9
+ const content = document.createElement('span'); content.className = 'help-content'; content.textContent = text; content.id = `field-help-${++helpSequence}`;
10
+ summary.setAttribute('aria-describedby', content.id); help.append(summary, content); label.append(help);
11
+ help.addEventListener('keydown', event => { if (event.key === 'Escape') { help.open = false; summary.focus(); } });
12
+ }
3
13
  const csrfHeader = { 'x-pygmalion-csrf': '1' };
4
14
 
5
15
  const views = { auth: $('#auth-view'), app: $('#app-view') };
6
16
  const editorView = $('#editor-view');
7
- const lifeView = $('#life-view');
8
- const memeView = $('#meme-view');
9
- const deviceView = $('#device-view');
10
- const rolesView = $('#roles-view');
11
- const pageTitle = $('#page-title');
17
+ const lifeView = $('#life-view');
18
+ const memeView = $('#meme-view');
19
+ const deviceView = $('#device-view');
20
+ const rolesView = $('#roles-view');
21
+ const pageTitle = $('#page-title');
12
22
 
13
23
  let me = null;
14
24
  let roles = [];
@@ -16,27 +26,27 @@ let editingRoleId = null; // null = 新建
16
26
  let lifeRoleId = null;
17
27
  let memeRoleId = null;
18
28
 
19
- function show(view) {
20
- views.auth.classList.toggle('hidden', view !== 'auth');
21
- views.app.classList.toggle('hidden', view !== 'app');
22
- rolesView.classList.toggle('hidden', view !== 'app');
23
- editorView.classList.add('hidden');
29
+ function show(view) {
30
+ views.auth.classList.toggle('hidden', view !== 'auth');
31
+ views.app.classList.toggle('hidden', view !== 'app');
32
+ rolesView.classList.toggle('hidden', view !== 'app');
33
+ editorView.classList.add('hidden');
34
+ lifeView.classList.add('hidden');
35
+ memeView.classList.add('hidden');
36
+ deviceView.classList.add('hidden');
37
+ }
38
+ function setActiveNav(name) {
39
+ document.querySelectorAll('[data-nav]').forEach((el) => el.classList.toggle('active', el.dataset.nav === name));
40
+ }
41
+ function showRoles() {
42
+ editorView.classList.add('hidden');
24
43
  lifeView.classList.add('hidden');
25
44
  memeView.classList.add('hidden');
26
- deviceView.classList.add('hidden');
27
- }
28
- function setActiveNav(name) {
29
- document.querySelectorAll('[data-nav]').forEach((el) => el.classList.toggle('active', el.dataset.nav === name));
30
- }
31
- function showRoles() {
32
- editorView.classList.add('hidden');
33
- lifeView.classList.add('hidden');
34
- memeView.classList.add('hidden');
35
- deviceView.classList.add('hidden');
36
- rolesView.classList.remove('hidden');
37
- pageTitle.textContent = '角色空间';
38
- setActiveNav('roles');
39
- }
45
+ deviceView.classList.add('hidden');
46
+ rolesView.classList.remove('hidden');
47
+ pageTitle.textContent = '角色空间';
48
+ setActiveNav('roles');
49
+ }
40
50
  function status(msg, isErr = false) {
41
51
  const bar = $('#status-bar');
42
52
  bar.textContent = msg;
@@ -62,9 +72,9 @@ function esc(s) {
62
72
 
63
73
  /* ------------------------------- 认证 ------------------------------- */
64
74
  let isRegister = false;
65
- function setAuthMode() {
66
- $('#auth-submit').textContent = isRegister ? '注册' : '登录';
67
- $('#auth-display').parentElement.classList.toggle('hidden', !isRegister);
75
+ function setAuthMode() {
76
+ $('#auth-submit').textContent = isRegister ? '注册' : '登录';
77
+ $('#auth-display').parentElement.classList.toggle('hidden', !isRegister);
68
78
  }
69
79
  $('#auth-toggle').addEventListener('click', () => { isRegister = !isRegister; setAuthMode(); $('#auth-error').textContent = ''; });
70
80
  $('#auth-form').addEventListener('submit', async (e) => {
@@ -97,29 +107,30 @@ $('#btn-password').addEventListener('click', () => {
97
107
  });
98
108
 
99
109
  /* ------------------------------- 主界面 ------------------------------- */
100
- async function boot() {
101
- show('app');
102
- $('#me-label').textContent = `${me.displayName || me.qqNumber}(${me.qqNumber})`;
103
- $('#me-initial').textContent = String(me.displayName || me.qqNumber || 'P').trim().slice(0, 1).toUpperCase();
104
- await loadRoles();
105
- }
110
+ async function boot() {
111
+ show('app');
112
+ $('#me-label').textContent = `${me.displayName || me.qqNumber}(${me.qqNumber})`;
113
+ $('#me-initial').textContent = String(me.displayName || me.qqNumber || 'P').trim().slice(0, 1).toUpperCase();
114
+ await loadRoles();
115
+ }
106
116
  async function loadRoles() {
107
117
  const r = await api('/api/me');
108
118
  me = r.account; roles = r.roles || [];
109
119
  renderRoles();
110
120
  }
111
121
  function bindingText(role) {
122
+ if (role.binding?.peer) return `已绑定 ${role.binding.peer.peerId} · ${role.binding.peer.adapterId}`;
112
123
  if (role.binding?.openid) return `已绑定 openid ${role.binding.openid}` + (role.binding.botAppId ? ` · AppID ${role.binding.botAppId}` : '');
113
124
  return '未绑定(首个与之聊天的 QQ 用户自动成为拥有者)';
114
125
  }
115
- function botStatusLabel(bot) {
116
- if (!bot?.configured) return '未配置机器人';
117
- if (bot.enabled === false) return '已休眠';
118
- return bot.status?.state === 'ready' ? '机器人已连接' : '机器人未连接';
119
- }
120
- function botStatusDetail(bot) {
121
- if (!bot?.configured) return '在编辑页填写 QQ 机器人的 AppID/AppSecret 即可开始聊天。';
122
- if (bot.enabled === false) return '角色已休眠:QQ 接入、主动唤醒和正在运行的脚本均已停止。';
126
+ function botStatusLabel(bot) {
127
+ if (!bot?.configured) return '未配置机器人';
128
+ if (bot.enabled === false) return '已休眠';
129
+ return bot.status?.state === 'ready' ? '机器人已连接' : '机器人未连接';
130
+ }
131
+ function botStatusDetail(bot) {
132
+ if (!bot?.configured) return '在编辑页填写 QQ 机器人的 AppID/AppSecret 即可开始聊天。';
133
+ if (bot.enabled === false) return '角色已休眠:QQ 接入、主动唤醒和正在运行的脚本均已停止。';
123
134
  const s = bot.status?.state;
124
135
  const d = bot.status?.detail ? `(${bot.status.detail})` : '';
125
136
  const map = {
@@ -134,26 +145,26 @@ function botStatusDetail(bot) {
134
145
  function renderRoles() {
135
146
  const list = $('#role-list');
136
147
  if (!roles.length) {
137
- list.innerHTML = '<p class="muted">还没有角色。点「+ 新建角色」创建你的第一个角色,然后在编辑页为它配置 QQ 机器人(AppID/AppSecret),即可在 QQ 里开始聊天。</p>';
148
+ list.innerHTML = '<p class="muted">还没有角色。点「+ 新建角色」创建你的第一个角色,然后在编辑页为它选择通信实现并配置聊天连接。</p>';
138
149
  return;
139
150
  }
140
151
  list.innerHTML = roles.map((r) => `
141
152
  <div class="role-card">
142
153
  <div class="role-main">
143
154
  <div class="row"><strong>${esc(r.persona?.name || '未命名角色')}</strong>
144
- <span class="tag ${r.bot?.enabled === false ? 'sleeping' : r.bot?.configured && r.bot.status?.state === 'ready' ? 'ok' : ''}">${botStatusLabel(r.bot)}</span>
145
- <span class="tag ${r.binding?.openid ? 'ok' : ''}">${r.binding?.openid ? '已绑定' : '未绑定'}</span>
155
+ <span class="tag ${r.bot?.enabled === false ? 'sleeping' : r.bot?.configured && r.bot.status?.state === 'ready' ? 'ok' : ''}">${botStatusLabel(r.bot)}</span>
156
+ <span class="tag ${(r.binding?.peer || r.binding?.openid) ? 'ok' : ''}">${(r.binding?.peer || r.binding?.openid) ? '已绑定' : '未绑定'}</span>
146
157
  ${r.life?.hasScript ? '<span class="tag ok">有脚本</span>' : ''}
147
158
  </div>
148
- <div class="muted">${esc(r.persona?.personality || '还没有填写性格')}${r.persona?.age ? ` · ${esc(r.persona.age)} 岁` : ''}</div>
149
- <div class="muted">${r.bot?.configured ? botStatusDetail(r.bot) : '尚未连接 QQ 机器人'}</div>
150
- <div class="muted">${r.binding?.openid ? '已与拥有者绑定' : '等待第一次 QQ 对话完成绑定'}</div>
159
+ <div class="muted">${esc(r.persona?.personality || '还没有填写性格')}${r.persona?.age ? ` · ${esc(r.persona.age)} 岁` : ''}</div>
160
+ <div class="muted">${r.bot?.configured ? botStatusDetail(r.bot) : '尚未配置聊天连接'}</div>
161
+ <div class="muted">${(r.binding?.peer || r.binding?.openid) ? '已与拥有者绑定' : '等待第一次私人对话完成绑定'}</div>
151
162
  </div>
152
163
  <div class="row role-actions">
153
164
  <button class="ghost" data-act="edit" data-id="${esc(r.roleId)}">编辑</button>
154
165
  <button class="ghost" data-act="life" data-id="${esc(r.roleId)}">脚本</button>
155
- <button class="ghost" data-act="memes" data-id="${esc(r.roleId)}">表情包</button>
156
- ${r.bot?.configured ? `<button class="ghost ${r.bot.enabled === false ? 'wake' : 'sleep'}" data-act="sleep" data-id="${esc(r.roleId)}">${r.bot.enabled === false ? '唤醒' : '休眠'}</button>` : ''}
166
+ <button class="ghost" data-act="memes" data-id="${esc(r.roleId)}">表情包</button>
167
+ ${r.bot?.configured ? `<button class="ghost ${r.bot.enabled === false ? 'wake' : 'sleep'}" data-act="sleep" data-id="${esc(r.roleId)}">${r.bot.enabled === false ? '唤醒' : '休眠'}</button>` : ''}
157
168
  <button class="ghost" data-act="reset" data-id="${esc(r.roleId)}">重置绑定</button>
158
169
  <button class="ghost danger" data-act="del" data-id="${esc(r.roleId)}">删除</button>
159
170
  </div>
@@ -167,8 +178,8 @@ $('#role-list').addEventListener('click', async (e) => {
167
178
  try {
168
179
  if (act === 'edit') openEditor(rid);
169
180
  else if (act === 'life') openLife(rid);
170
- else if (act === 'memes') openMemes(rid);
171
- else if (act === 'sleep') await toggleSleep(rid);
181
+ else if (act === 'memes') openMemes(rid);
182
+ else if (act === 'sleep') await toggleSleep(rid);
172
183
  else if (act === 'reset') { await api(`/api/me/roles/${rid}/reset-binding`, 'POST'); status('绑定已重置,下一位聊天者将成为拥有者'); await loadRoles(); }
173
184
  else if (act === 'del') {
174
185
  const name = roles.find((r) => r.roleId === rid)?.persona?.name || '该角色';
@@ -200,17 +211,23 @@ function openEditor(rid) {
200
211
  $('#f-apiurl').value = m.apiUrl || '';
201
212
  $('#f-apikey').value = m.apiKey || '';
202
213
  $('#f-model-vision').checked = m.vision === true;
214
+ const rp = role?.roleplay || {};
215
+ $('#f-roleplay-enabled').checked = rp.enabled === true;
216
+ $('#f-roleplay-provider').value = rp.provider || '';
217
+ $('#f-roleplay-model').value = rp.model || '';
218
+ $('#f-roleplay-apiurl').value = rp.apiUrl || '';
219
+ $('#f-roleplay-apikey').value = '';
220
+ $('#f-roleplay-apikey').placeholder = rp.keyConfigured ? '已配置;留空保持不变' : '填写角色生成模型的 API Key';
221
+ $('#f-roleplay-retries').value = rp.retries ?? 2;
222
+ $('#f-roleplay-input').value = rp.maxInputChars ?? 500000;
223
+ $('#roleplay-status-line').textContent = ({disabled:'独立角色生成已关闭',normal:'独立角色生成已启用',retrying:'角色模型退避重试中',fallback:'角色模型暂不可用,当前由主模型代写',retryable_error:'本次生成未完成,等待后续重试'})[role?.roleplayStatus?.status ?? (rp.enabled?'normal':'disabled')];
203
224
  const pr = role?.proactive || {};
204
225
  $('#f-proactive-enabled').checked = pr.enabled !== false;
205
226
  $('#f-maxwake').value = pr.maxWakeupsPerDay ?? 5;
206
227
  $('#f-quiet').value = (pr.quietHours || []).join(', ');
207
- $('#f-archive').value = pr.archiveIdleMinutes ?? 45;
208
- $('#f-evening').value = pr.eveningCheck || '20:00';
209
- const mr = pr.messageReview || {};
210
- $('#f-message-review-enabled').checked = mr.enabled !== false;
211
- $('#f-message-review-provider').value = mr.provider || '';
212
- $('#f-message-review-model').value = mr.model || '';
213
- const mc = pr.memeCollection || {};
228
+ $('#f-archive').value = pr.archiveIdleMinutes ?? 45;
229
+ $('#f-evening').value = pr.eveningCheck || '20:00';
230
+ const mc = pr.memeCollection || {};
214
231
  $('#f-meme-enabled').checked = mc.enabled === true;
215
232
  $('#f-meme-interval').value = mc.intervalDays ?? 7;
216
233
  const v = mc.vision || {};
@@ -218,38 +235,67 @@ function openEditor(rid) {
218
235
  $('#f-meme-vision-model').value = v.model || '';
219
236
  $('#f-meme-vision-apiurl').value = v.apiUrl || '';
220
237
  $('#f-meme-vision-apikey').value = v.apiKey || '';
221
- $('#editor-error').textContent = '';
222
- fillBotForm(role);
223
- fillVoiceForm(role);
224
- rolesView.classList.add('hidden');
225
- editorView.classList.remove('hidden');
238
+ $('#editor-error').textContent = '';
239
+ fillBotForm(role);
240
+ fillVoiceForm(role);
241
+ rolesView.classList.add('hidden');
242
+ editorView.classList.remove('hidden');
226
243
  lifeView.classList.add('hidden');
227
244
  memeView.classList.add('hidden');
228
- deviceView.classList.add('hidden');
229
- pageTitle.textContent = rid ? '编辑角色' : '创建角色';
230
- setActiveNav('roles');
245
+ deviceView.classList.add('hidden');
246
+ pageTitle.textContent = rid ? '编辑角色' : '创建角色';
247
+ setActiveNav('roles');
231
248
  void renderDeviceChecks(p.devices || []);
232
249
  editorView.scrollIntoView({ behavior: 'smooth' });
233
250
  }
234
- function fillBotForm(role) {
251
+ let channelAdapters = [], channelGeneration = 0, channelLoading = false, currentChannel;
252
+ function renderChannelFields(useSaved = false) {
253
+ const descriptor = channelAdapters.find(item => item.id === $('#f-channel-adapter').value);
254
+ const box = $('#channel-fields'); box.replaceChildren();
255
+ for (const field of descriptor?.fields ?? []) {
256
+ const label = document.createElement('label'); label.textContent = field.label; fieldHelp(label, field.help || (field.type === 'secret' ? '凭据只写入,不回显;编辑时留空保留已保存值。' : '此项由当前扩展定义,配置要求以该实现说明为准。'));
257
+ const input = document.createElement(field.type === 'select' ? 'select' : 'input');
258
+ input.dataset.field = field.key; input.dataset.type = field.type;
259
+ if (field.type === 'select') for (const option of field.options) { const node = document.createElement('option'); node.value = option.value; node.textContent = option.label; input.append(node); }
260
+ else input.type = field.type === 'secret' ? 'password' : field.type === 'boolean' ? 'checkbox' : 'text';
261
+ const value = useSaved ? currentChannel?.config?.[field.key] ?? field.default : field.default;
262
+ if (field.type === 'boolean') input.checked = value === true;
263
+ else if (field.type === 'secret') input.placeholder = useSaved && currentChannel?.secrets?.[field.key] ? '已保存;留空保持' : '';
264
+ else input.value = value ?? '';
265
+ label.append(input); box.append(label);
266
+ }
267
+ }
268
+ async function fillChannelFields(role) {
269
+ const generation = ++channelGeneration; if (!role) return; channelLoading = true; currentChannel = role.bot;
270
+ try {
271
+ const {adapters} = await api('/api/me/channel-adapters'); if (generation !== channelGeneration || editingRoleId !== role.roleId) return;
272
+ channelAdapters = adapters; const select = $('#f-channel-adapter'); select.replaceChildren();
273
+ for (const descriptor of adapters) { const option = document.createElement('option'); option.value = descriptor.id; option.textContent = descriptor.name; select.append(option); }
274
+ if (currentChannel?.adapterId) {
275
+ if (!adapters.some(item => item.id === currentChannel.adapterId)) { const option = document.createElement('option'); option.value = currentChannel.adapterId; option.textContent = '当前通信实现不可用,配置已保留'; select.append(option); }
276
+ select.value = currentChannel.adapterId;
277
+ }
278
+ renderChannelFields(true);
279
+ } catch (error) { $('#bot-error').textContent = error.message; }
280
+ finally { if (generation === channelGeneration) channelLoading = false; }
281
+ }
282
+ $('#f-channel-adapter').addEventListener('change', () => renderChannelFields($('#f-channel-adapter').value === currentChannel?.adapterId));
283
+ function fillBotForm(role) {
235
284
  const bot = role?.bot || {};
236
- $('#f-appid').value = bot.qqAppId || '';
237
- $('#f-appsecret').value = '';
238
- $('#f-sandbox').checked = bot.configured ? bot.sandbox !== false : true;
239
- $('#f-streaming').checked = bot.configured ? bot.streaming === true : false;
285
+ void fillChannelFields(role);
240
286
  $('#f-chatwindow').value = Math.round((bot.withinChatWindowMs || 300000) / 60000);
241
- $('#bot-status-line').textContent = botStatusDetail(bot);
242
- const sleep = $('#btn-toggle-sleep');
243
- sleep.classList.toggle('hidden', !bot.configured);
244
- sleep.textContent = bot.enabled === false ? '唤醒角色' : '休眠角色';
245
- sleep.classList.toggle('wake', bot.enabled === false);
246
- sleep.classList.toggle('sleep', bot.enabled !== false);
287
+ $('#bot-status-line').textContent = botStatusDetail(bot);
288
+ const sleep = $('#btn-toggle-sleep');
289
+ sleep.classList.toggle('hidden', !bot.configured);
290
+ sleep.textContent = bot.enabled === false ? '唤醒角色' : '休眠角色';
291
+ sleep.classList.toggle('wake', bot.enabled === false);
292
+ sleep.classList.toggle('sleep', bot.enabled !== false);
247
293
  $('#btn-del-bot').classList.toggle('hidden', !bot.configured);
248
294
  $('#bot-form').classList.toggle('hidden', !role);
249
295
  $('#bot-error').textContent = '';
250
296
  }
251
297
  $('#btn-new-role').addEventListener('click', () => openEditor(null));
252
- $('#btn-close-editor').addEventListener('click', showRoles);
298
+ $('#btn-close-editor').addEventListener('click', showRoles);
253
299
  $('#role-form').addEventListener('submit', async (e) => {
254
300
  e.preventDefault();
255
301
  const persona = {
@@ -274,14 +320,9 @@ $('#role-form').addEventListener('submit', async (e) => {
274
320
  enabled: $('#f-proactive-enabled').checked,
275
321
  maxWakeupsPerDay: Number($('#f-maxwake').value) || 0,
276
322
  quietHours: $('#f-quiet').value.split(',').map((s) => s.trim()).filter(Boolean),
277
- archiveIdleMinutes: Number($('#f-archive').value) || 0,
278
- eveningCheck: $('#f-evening').value.trim() || '20:00',
279
- messageReview: {
280
- enabled: $('#f-message-review-enabled').checked,
281
- provider: $('#f-message-review-provider').value.trim(),
282
- model: $('#f-message-review-model').value.trim(),
283
- },
284
- memeCollection: {
323
+ archiveIdleMinutes: Number($('#f-archive').value) || 0,
324
+ eveningCheck: $('#f-evening').value.trim() || '20:00',
325
+ memeCollection: {
285
326
  enabled: $('#f-meme-enabled').checked,
286
327
  intervalDays: Number($('#f-meme-interval').value) || 7,
287
328
  vision: {
@@ -292,7 +333,16 @@ $('#role-form').addEventListener('submit', async (e) => {
292
333
  },
293
334
  },
294
335
  };
295
- const body = { persona, model, proactive };
336
+ const roleplay = {
337
+ enabled: $('#f-roleplay-enabled').checked,
338
+ provider: $('#f-roleplay-provider').value.trim(),
339
+ model: $('#f-roleplay-model').value.trim(),
340
+ apiUrl: $('#f-roleplay-apiurl').value.trim(),
341
+ apiKey: $('#f-roleplay-apikey').value.trim(),
342
+ retries: Number($('#f-roleplay-retries').value),
343
+ maxInputChars: Number($('#f-roleplay-input').value),
344
+ };
345
+ const body = { persona, model, proactive, roleplay };
296
346
  try {
297
347
  if (editingRoleId) {
298
348
  await api(`/api/me/roles/${editingRoleId}`, 'PUT', body);
@@ -301,7 +351,7 @@ $('#role-form').addEventListener('submit', async (e) => {
301
351
  const r = await api('/api/me/roles', 'POST', body);
302
352
  status(`角色「${r.role?.persona?.name || '新角色'}」已创建`);
303
353
  }
304
- showRoles();
354
+ showRoles();
305
355
  await loadRoles();
306
356
  } catch (err) { $('#editor-error').textContent = err.message; }
307
357
  });
@@ -315,39 +365,75 @@ async function renderDeviceChecks(selected = []) {
315
365
  if (!list.length) { box.innerHTML = '<span class="muted">还没有设备——先点右上「我的设备」登记。</span>'; return; }
316
366
  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('');
317
367
  }
368
+ let deviceDrivers = [], registeredDevices = [], editingDevice = null;
369
+ function renderDeviceFields() {
370
+ const driver = deviceDrivers.find(item => item.id === $('#device-driver').value);
371
+ const box = $('#device-fields'); box.replaceChildren();
372
+ for (const field of driver?.fields ?? []) {
373
+ const label = document.createElement('label'); label.textContent = field.label; fieldHelp(label, field.help || (field.type === 'secret' ? '凭据只写入,不回显;编辑时留空保留已保存值。' : '此项由当前扩展定义,配置要求以该实现说明为准。'));
374
+ const input = document.createElement(field.type === 'select' ? 'select' : 'input');
375
+ input.dataset.field = field.key; input.dataset.type = field.type;
376
+ if (field.type === 'select') for (const option of field.options) { const node = document.createElement('option'); node.value = option.value; node.textContent = option.label; input.append(node); }
377
+ else input.type = field.type === 'secret' ? 'password' : field.type === 'boolean' ? 'checkbox' : 'text';
378
+ if (field.type === 'boolean') input.checked = field.default === true; else input.value = field.default ?? '';
379
+ label.append(input); box.append(label);
380
+ }
381
+ $('#device-add').disabled = !driver;
382
+ if (editingDevice) for (const input of box.querySelectorAll('[data-field]')) {
383
+ const value = editingDevice.config?.[input.dataset.field];
384
+ if (input.dataset.type === 'secret') input.placeholder = editingDevice.secrets?.[input.dataset.field] ? '已保存;留空保留' : '尚未配置';
385
+ else if (input.dataset.type === 'boolean') input.checked = value === true; else if (value !== undefined) input.value = value;
386
+ }
387
+ }
388
+ $('#device-driver').addEventListener('change', renderDeviceFields);
318
389
  async function renderDevicePanel() {
319
- const list = (await api('/api/me/devices')).devices || [];
390
+ const [inventory, registry] = await Promise.all([api('/api/me/devices'), api('/api/me/device-drivers')]);
391
+ const list = inventory.devices || []; registeredDevices = list; deviceDrivers = registry.drivers || [];
392
+ const selector = $('#device-driver'); selector.replaceChildren();
393
+ for (const driver of deviceDrivers) { const option = document.createElement('option'); option.value = driver.id; option.textContent = driver.name; selector.append(option); }
394
+ editingDevice = null; $('#device-driver').disabled = false; $('#device-add').textContent = '添加设备'; $('#device-cancel').classList.add('hidden');
395
+ renderDeviceFields();
320
396
  const box = $('#device-list');
321
397
  if (!list.length) { box.innerHTML = '<p class="muted">还没有设备。</p>'; return; }
322
398
  box.innerHTML = list.map((d) => `<div class="row">
323
399
  <span class="run-info">${esc(d.alias)} <span class="muted">(${esc(d.kind)})</span></span>
324
- <button class="ghost danger device-del" data-id="${esc(d.id)}">删除</button>
400
+ <button class="ghost device-edit" data-id="${esc(d.id)}" ${d.available === false ? 'disabled' : ''}>编辑</button><button class="ghost danger device-del" data-id="${esc(d.id)}">删除</button>
325
401
  </div>`).join('');
326
402
  }
327
- $('#btn-devices').addEventListener('click', () => {
328
- rolesView.classList.add('hidden');
329
- editorView.classList.add('hidden');
403
+ $('#btn-devices').addEventListener('click', () => {
404
+ rolesView.classList.add('hidden');
405
+ editorView.classList.add('hidden');
330
406
  lifeView.classList.add('hidden');
331
407
  memeView.classList.add('hidden');
332
- deviceView.classList.remove('hidden');
333
- pageTitle.textContent = '我的设备';
334
- setActiveNav('devices');
335
- void renderDevicePanel();
336
- });
337
- document.querySelector('[data-nav="roles"]').addEventListener('click', showRoles);
338
- $('#btn-close-devices').addEventListener('click', showRoles);
408
+ deviceView.classList.remove('hidden');
409
+ pageTitle.textContent = '我的设备';
410
+ setActiveNav('devices');
411
+ void renderDevicePanel();
412
+ });
413
+ document.querySelector('[data-nav="roles"]').addEventListener('click', showRoles);
414
+ $('#btn-close-devices').addEventListener('click', showRoles);
339
415
  $('#device-add').addEventListener('click', async () => {
340
416
  const alias = $('#device-alias').value.trim();
341
417
  if (!alias) return;
342
418
  try {
343
- await api('/api/me/devices', 'POST', { alias, kind: 'monsterparty' });
419
+ const config = Object.fromEntries([...document.querySelectorAll('#device-fields [data-field]')].map(input => [input.dataset.field, input.dataset.type === 'boolean' ? input.checked : input.value]));
420
+ if (editingDevice) await api(`/api/me/devices/${encodeURIComponent(editingDevice.id)}`, 'PUT', { alias, config, revision: editingDevice.revision ?? 0 });
421
+ else await api('/api/me/devices', 'POST', { alias, kind: $('#device-driver').value, config });
344
422
  $('#device-alias').value = '';
345
423
  status('设备已登记');
346
424
  await renderDevicePanel();
347
425
  } catch (err) { status(err.message, true); }
348
426
  });
349
427
  $('#device-alias').addEventListener('keydown', (e) => { if (e.key === 'Enter') $('#device-add').click(); });
428
+ $('#device-cancel').addEventListener('click', () => { $('#device-alias').value = ''; void renderDevicePanel(); });
350
429
  $('#device-list').addEventListener('click', async (e) => {
430
+ const edit = e.target.closest('button.device-edit');
431
+ if (edit) {
432
+ editingDevice = registeredDevices.find(item => item.id === edit.dataset.id);
433
+ $('#device-driver').value = editingDevice.kind; $('#device-driver').disabled = true;
434
+ $('#device-alias').value = editingDevice.alias; $('#device-add').textContent = '保存设备'; $('#device-cancel').classList.remove('hidden');
435
+ renderDeviceFields(); return;
436
+ }
351
437
  const btn = e.target.closest('button.device-del');
352
438
  if (!btn) return;
353
439
  if (!confirm('删除这台设备?它在各角色上的勾选也会移除。')) return;
@@ -361,14 +447,12 @@ $('#device-list').addEventListener('click', async (e) => {
361
447
  /* ------------------------------- QQ 机器人 ------------------------------- */
362
448
  $('#bot-form').addEventListener('submit', async (e) => {
363
449
  e.preventDefault();
364
- if (!editingRoleId) return;
365
- const body = {
366
- qqAppId: $('#f-appid').value.trim(),
367
- qqSecret: $('#f-appsecret').value.trim() || undefined,
368
- sandbox: $('#f-sandbox').checked,
369
- streaming: $('#f-streaming').checked,
370
- withinChatWindowMs: (Number($('#f-chatwindow').value) || 5) * 60000,
371
- enabled: roles.find((r) => r.roleId === editingRoleId)?.bot?.enabled !== false,
450
+ if (!editingRoleId || channelLoading) return;
451
+ const body = {
452
+ adapterId: $('#f-channel-adapter').value,
453
+ config: Object.fromEntries([...document.querySelectorAll('#channel-fields [data-field]')].map(input => [input.dataset.field, input.dataset.type === 'boolean' ? input.checked : input.value])),
454
+ withinChatWindowMs: (Number($('#f-chatwindow').value) || 5) * 60000,
455
+ enabled: roles.find((r) => r.roleId === editingRoleId)?.bot?.enabled !== false,
372
456
  };
373
457
  try {
374
458
  await api(`/api/me/roles/${editingRoleId}/bot`, 'PUT', body);
@@ -376,53 +460,117 @@ $('#bot-form').addEventListener('submit', async (e) => {
376
460
  await loadRoles();
377
461
  openEditor(editingRoleId);
378
462
  } catch (err) { $('#bot-error').textContent = err.message; }
379
- });
380
- async function toggleSleep(rid) {
381
- const role = roles.find((r) => r.roleId === rid);
382
- const bot = role?.bot;
383
- if (!bot?.configured) return;
384
- const sleeping = bot.enabled === false;
385
- const name = role?.persona?.name || '该角色';
386
- if (!sleeping && !confirm(`让「${name}」进入休眠?\n\nQQ 接入、主动互动和正在运行的生活/设备脚本都会停止;角色资料与记忆会保留。`)) return;
387
- try {
388
- await api(`/api/me/roles/${rid}/bot`, 'PUT', { enabled: sleeping });
389
- status(sleeping ? `「${name}」已唤醒,正在连接 QQ。` : `「${name}」已进入休眠。`);
390
- await loadRoles();
391
- if (editingRoleId === rid) openEditor(rid);
392
- } catch (err) { status(err.message, true); }
393
- }
394
- function fillVoiceForm(role) {
395
- const v = role?.voice || {};
396
- $('#voice-form').classList.toggle('hidden', !role);
397
- $('#f-voice-enabled').checked = v.enabled === true;
398
- $('#f-mimo-key').value = '';
399
- $('#f-mimo-model').value = v.model || 'mimo-v2.5-tts-voiceclone';
400
- $('#f-voice-role').value = v.rolePrompt || '';
401
- $('#voice-reference-info').textContent = v.reference ? `${v.reference.name} · ${(v.reference.bytes / 1024 / 1024).toFixed(2)} MB` : '支持 WAV / MP3;Base64 编码后不超过 10MB。';
402
- $('#voice-status-line').textContent = v.configured && v.reference ? (v.enabled ? '已就绪:导演可发送语音消息。' : '已配置,尚未启用。') : '请配置 API Key 并上传参考音频。';
403
- $('#voice-error').textContent = '';
404
- }
405
- $('#voice-form').addEventListener('submit', async (e) => {
406
- e.preventDefault(); if (!editingRoleId) return;
407
- try {
408
- const r = await api(`/api/me/roles/${editingRoleId}/voice`, 'PUT', { enabled: $('#f-voice-enabled').checked, apiKey: $('#f-mimo-key').value.trim(), model: $('#f-mimo-model').value.trim(), rolePrompt: $('#f-voice-role').value.trim() });
409
- const role = roles.find((x) => x.roleId === editingRoleId); if (role) role.voice = r.voice;
410
- fillVoiceForm(role); status('语音配置已保存');
411
- } catch (err) { $('#voice-error').textContent = err.message; }
412
- });
413
- $('#btn-voice-reference').addEventListener('click', async () => {
414
- if (!editingRoleId) return; const input = $('#voice-reference'); const file = input.files?.[0];
415
- if (!file) { $('#voice-error').textContent = '请先选择 WAV 或 MP3 文件'; return; }
416
- try {
417
- const bytes = new Uint8Array(await file.arrayBuffer());
418
- const r = await api(`/api/me/roles/${editingRoleId}/voice/reference`, 'POST', { data: bytesToBase64(bytes), mime: file.type || (file.name.toLowerCase().endsWith('.mp3') ? 'audio/mpeg' : 'audio/wav'), name: file.name });
419
- const role = roles.find((x) => x.roleId === editingRoleId); if (role) role.voice = r.voice;
420
- input.value = ''; fillVoiceForm(role); status('参考音频已上传');
421
- } catch (err) { $('#voice-error').textContent = err.message; }
422
- });
423
- $('#btn-toggle-sleep').addEventListener('click', () => {
424
- if (editingRoleId) void toggleSleep(editingRoleId);
425
- });
463
+ });
464
+ async function toggleSleep(rid) {
465
+ const role = roles.find((r) => r.roleId === rid);
466
+ const bot = role?.bot;
467
+ if (!bot?.configured) return;
468
+ const sleeping = bot.enabled === false;
469
+ const name = role?.persona?.name || '该角色';
470
+ if (!sleeping && !confirm(`让「${name}」进入休眠?\n\n聊天连接、主动互动和正在运行的生活/设备脚本都会停止;角色资料与记忆会保留。`)) return;
471
+ try {
472
+ await api(`/api/me/roles/${rid}/bot`, 'PUT', { enabled: sleeping });
473
+ status(sleeping ? `「${name}」已唤醒,正在连接聊天服务。` : `「${name}」已进入休眠。`);
474
+ await loadRoles();
475
+ if (editingRoleId === rid) openEditor(rid);
476
+ } catch (err) { status(err.message, true); }
477
+ }
478
+ let voiceFormState, voiceFormGeneration = 0, voiceLoading = false;
479
+ const voiceInputs = new Map();
480
+ async function fillVoiceForm(role) {
481
+ const generation = ++voiceFormGeneration;
482
+ $('#voice-form').classList.toggle('hidden', !role);
483
+ if (!role) return;
484
+ voiceLoading = true;
485
+ voiceFormState = role.voice;
486
+ $('#voice-error').textContent = '';
487
+ try {
488
+ const data = await api('/api/me/tts-providers');
489
+ if (generation !== voiceFormGeneration || editingRoleId !== role.roleId) return;
490
+ const select = $('#f-voice-provider'); select.replaceChildren();
491
+ const providers = [...data.providers];
492
+ if (!providers.some(item => item.id === voiceFormState.providerId)) providers.push({ id: voiceFormState.providerId, name: '当前服务不可用' });
493
+ for (const provider of providers) {
494
+ const option = document.createElement('option'); option.value = provider.id; option.textContent = provider.name; select.append(option);
495
+ }
496
+ select.value = voiceFormState.providerId;
497
+ renderVoiceFields();
498
+ } catch (err) { if (generation === voiceFormGeneration) $('#voice-error').textContent = err.message; }
499
+ finally { if (generation === voiceFormGeneration) voiceLoading = false; }
500
+ }
501
+ function renderVoiceFields() {
502
+ const v = voiceFormState;
503
+ $('#f-voice-enabled').checked = v.enabled === true;
504
+ $('#voice-status-line').textContent = v.ready ? '已就绪,可合成语音。' : v.reason || '已配置,尚未启用。';
505
+ const container = $('#voice-fields'); container.replaceChildren(); voiceInputs.clear();
506
+ for (const field of v.fields || []) {
507
+ const label = document.createElement('label'); label.textContent = field.label; fieldHelp(label, field.help || (field.type === 'secret' ? '凭据只写入,不回显;编辑时留空保留已保存值。' : '此项由当前扩展定义,配置要求以该实现说明为准。'));
508
+ let input = document.createElement(field.type === 'select' ? 'select' : 'input');
509
+ if (field.type === 'select') {
510
+ for (const choice of field.options) {
511
+ const option = document.createElement('option'); option.value = choice.value; option.textContent = choice.label; input.append(option);
512
+ }
513
+ input.value = v.values[field.key] ?? field.default ?? '';
514
+ } else if (field.type === 'audio') {
515
+ input.type = 'file'; input.accept = (field.accept || []).join(',');
516
+ const info = document.createElement('small'); info.textContent = v.values[field.key]?.name || '尚未上传'; label.append(info);
517
+ const button = document.createElement('button'); button.type = 'button'; button.className = 'button secondary'; button.textContent = '保存配置并上传';
518
+ button.addEventListener('click', () => void uploadVoiceAudio(field.key, input)); label.append(input, button); container.append(label); continue;
519
+ } else if (field.type === 'boolean') { input.type = 'checkbox'; input.checked = v.values[field.key] === true; }
520
+ else {
521
+ input.type = field.type === 'secret' ? 'password' : 'text';
522
+ input.value = field.type === 'secret' ? '' : v.values[field.key] ?? '';
523
+ if (field.type === 'secret') { input.autocomplete = 'new-password'; input.placeholder = v.secrets[field.key] ? '已配置;留空保持,清空请勾选' : ''; }
524
+ }
525
+ label.append(input); voiceInputs.set(field.key, input);
526
+ if (field.type === 'secret' && v.secrets[field.key]) {
527
+ const clear = document.createElement('input'); clear.type = 'checkbox';
528
+ const hint = document.createElement('span'); hint.textContent = '清空此凭据'; label.append(clear, hint); input.clearSecret = clear;
529
+ }
530
+ container.append(label);
531
+ }
532
+ }
533
+ function voicePatch(enabled = $('#f-voice-enabled').checked) {
534
+ return { providerId: voiceFormState.providerId, revision: voiceFormState.revision, enabled,
535
+ values: Object.fromEntries([...voiceInputs].map(([key, input]) => [key,
536
+ input.clearSecret?.checked ? null : input.type === 'checkbox' ? input.checked : input.value])) };
537
+ }
538
+ $('#f-voice-provider').addEventListener('change', async (e) => {
539
+ const rid = editingRoleId, generation = ++voiceFormGeneration;
540
+ voiceLoading = true;
541
+ try {
542
+ const data = await api(`/api/me/roles/${rid}/voice?providerId=${encodeURIComponent(e.target.value)}`);
543
+ if (generation !== voiceFormGeneration || rid !== editingRoleId) return;
544
+ voiceFormState = data.voice; renderVoiceFields();
545
+ } catch (err) { if (generation === voiceFormGeneration) $('#voice-error').textContent = err.message; }
546
+ finally { if (generation === voiceFormGeneration) voiceLoading = false; }
547
+ });
548
+ $('#voice-form').addEventListener('submit', async (e) => {
549
+ e.preventDefault(); if (!editingRoleId || voiceLoading) return;
550
+ const rid = editingRoleId;
551
+ try {
552
+ const r = await api(`/api/me/roles/${rid}/voice`, 'PUT', voicePatch());
553
+ const role = roles.find((x) => x.roleId === rid); if (role) role.voice = r.voice;
554
+ if (rid === editingRoleId) void fillVoiceForm(role); status('语音配置已保存');
555
+ } catch (err) { if (rid === editingRoleId) $('#voice-error').textContent = err.message; }
556
+ });
557
+ async function uploadVoiceAudio(field, input) {
558
+ if (voiceLoading) return;
559
+ const rid = editingRoleId, file = input.files?.[0], enabled = $('#f-voice-enabled').checked;
560
+ if (!rid || !file) { $('#voice-error').textContent = '请先选择音频文件'; return; }
561
+ try {
562
+ const saved = await api(`/api/me/roles/${rid}/voice`, 'PUT', voicePatch(false));
563
+ const bytes = new Uint8Array(await file.arrayBuffer());
564
+ let r = await api(`/api/me/roles/${rid}/voice/assets`, 'POST', { field, providerId: saved.voice.providerId,
565
+ revision: saved.voice.revision, data: bytesToBase64(bytes), mime: file.type, name: file.name });
566
+ if (enabled !== r.voice.enabled) r = await api(`/api/me/roles/${rid}/voice`, 'PUT', { revision: r.voice.revision, enabled });
567
+ const role = roles.find((x) => x.roleId === rid); if (role) role.voice = r.voice;
568
+ if (rid === editingRoleId) void fillVoiceForm(role); status('音频已上传');
569
+ } catch (err) { if (rid === editingRoleId) $('#voice-error').textContent = err.message; }
570
+ }
571
+ $('#btn-toggle-sleep').addEventListener('click', () => {
572
+ if (editingRoleId) void toggleSleep(editingRoleId);
573
+ });
426
574
  $('#btn-del-bot').addEventListener('click', async () => {
427
575
  if (!editingRoleId) return;
428
576
  if (!confirm('删除该机器人的配置?连接将断开,之后可随时重新配置。')) return;
@@ -434,160 +582,160 @@ $('#btn-del-bot').addEventListener('click', async () => {
434
582
  } catch (err) { $('#bot-error').textContent = err.message; }
435
583
  });
436
584
 
437
- /* ------------------------------- 脚本监管 ------------------------------- */
438
- let lifeRefreshTimer = null;
439
- let scriptLogTimer = null;
440
- let currentScriptLog = null;
441
- const scriptSelection = {
442
- life: { kind: null, name: null },
443
- toy: { kind: null, name: null },
444
- };
445
-
446
- function selectScriptSpace(space) {
447
- document.querySelectorAll('[data-script-space]').forEach((button) => {
448
- const active = button.dataset.scriptSpace === space;
449
- button.classList.toggle('active', active);
450
- button.setAttribute('aria-selected', String(active));
451
- });
452
- $('#script-space-life').classList.toggle('hidden', space !== 'life');
453
- $('#script-space-toy').classList.toggle('hidden', space !== 'toy');
454
- }
455
-
456
- function selectAssetKind(group, kind) {
457
- const space = $(`#script-space-${group}`);
458
- space.querySelectorAll('[data-asset-kind]').forEach((button) => {
459
- const active = button.dataset.assetKind === kind;
460
- button.classList.toggle('active', active);
461
- button.setAttribute('aria-selected', String(active));
462
- });
463
- space.querySelectorAll('[data-asset-panel]').forEach((panel) => {
464
- panel.classList.toggle('hidden', panel.dataset.assetPanel !== kind);
465
- });
466
- }
467
-
468
- async function showFirstLog(group) {
469
- if (scriptSelection[group].name || window.matchMedia('(max-width: 700px)').matches) return;
470
- const attribute = group === 'life' ? 'data-log' : 'data-toylog';
471
- const first = $(`#${group}-logs button[${attribute}]`);
472
- if (first) await showScriptLog(group, first.getAttribute(attribute));
473
- }
474
-
475
- function resetInspector(group) {
476
- scriptSelection[group] = { kind: null, name: null };
477
- $(`#${group}-inspector-kind`).textContent = 'PREVIEW';
478
- $(`#${group}-inspector-title`).textContent = '选择一条日志或脚本';
479
- $(`#${group}-inspector-state`).textContent = '日志打开后自动追踪更新';
480
- $(`#${group}-preview-empty`).classList.remove('hidden');
481
- $(`#${group}-source`).classList.add('hidden');
482
- $(`#${group}-log-body`).classList.add('hidden');
483
- }
484
-
485
- function syncSelectedResource(group) {
486
- const selected = scriptSelection[group];
487
- $(`#script-space-${group}`).querySelectorAll('[data-resource-kind]').forEach((button) => {
488
- button.classList.toggle('active', button.dataset.resourceKind === selected.kind && button.dataset.resourceName === selected.name);
489
- });
490
- }
491
-
492
- function showInspector(group, kind, name, text, live = false) {
493
- scriptSelection[group] = { kind, name };
494
- const isLog = kind === 'log';
495
- $(`#${group}-inspector-kind`).textContent = isLog ? 'LOG OUTPUT' : 'SOURCE CODE';
496
- $(`#${group}-inspector-title`).textContent = name;
497
- $(`#${group}-inspector-state`).textContent = isLog && live ? '实时追踪中 · 每 2 秒更新' : (isLog ? '运行日志' : '只读源码');
498
- $(`#${group}-preview-empty`).classList.add('hidden');
499
- const source = $(`#${group}-source`);
500
- const log = $(`#${group}-log-body`);
501
- source.classList.toggle('hidden', isLog);
502
- log.classList.toggle('hidden', !isLog);
503
- (isLog ? log : source).textContent = text;
504
- syncSelectedResource(group);
505
- if (window.matchMedia('(max-width: 700px)').matches) {
506
- $(`#script-space-${group} .inspector-panel`).scrollIntoView({ behavior: 'smooth', block: 'start' });
507
- }
508
- }
509
-
510
- async function fetchScriptText(url) {
511
- const response = await fetch(url);
512
- const text = await response.text();
513
- if (!response.ok) {
514
- try { throw new Error(JSON.parse(text).error || `HTTP ${response.status}`); }
515
- catch (err) { if (err instanceof SyntaxError) throw new Error(`HTTP ${response.status}`); throw err; }
516
- }
517
- return text;
518
- }
519
-
520
- function startScriptLogPolling() {
521
- if (scriptLogTimer) return;
522
- scriptLogTimer = setInterval(async () => {
523
- if (!currentScriptLog || lifeView.classList.contains('hidden')) return;
524
- const { group, name } = currentScriptLog;
525
- const area = group === 'life' ? 'life' : 'toys';
526
- try {
527
- const text = await fetchScriptText(`/api/me/roles/${lifeRoleId}/${area}/log/${encodeURIComponent(name)}`);
528
- if (currentScriptLog?.group === group && currentScriptLog?.name === name) $(`#${group}-log-body`).textContent = text;
529
- } catch { /* 单次刷新失败忽略,下一轮再试 */ }
530
- }, 2000);
531
- }
532
-
533
- function stopScriptLogPolling() {
534
- if (scriptLogTimer) { clearInterval(scriptLogTimer); scriptLogTimer = null; }
535
- currentScriptLog = null;
536
- }
537
-
538
- async function showScriptLog(group, name) {
539
- const area = group === 'life' ? 'life' : 'toys';
540
- try {
541
- const text = await fetchScriptText(`/api/me/roles/${lifeRoleId}/${area}/log/${encodeURIComponent(name)}`);
542
- selectScriptSpace(group);
543
- selectAssetKind(group, 'logs');
544
- currentScriptLog = { group, name };
545
- showInspector(group, 'log', name, text, true);
546
- startScriptLogPolling();
547
- } catch (err) { status(err.message, true); }
548
- }
549
-
550
- async function showScriptSource(group, name) {
551
- const area = group === 'life' ? 'life' : 'toys';
552
- try {
553
- const text = await fetchScriptText(`/api/me/roles/${lifeRoleId}/${area}/script/${encodeURIComponent(name)}`);
554
- if (currentScriptLog?.group === group) currentScriptLog = null;
555
- selectScriptSpace(group);
556
- selectAssetKind(group, 'scripts');
557
- showInspector(group, 'source', name, text);
558
- } catch (err) { status(err.message, true); }
559
- }
560
-
561
- function resourceButton(group, kind, name, attribute) {
562
- const active = scriptSelection[group].kind === kind && scriptSelection[group].name === name ? ' active' : '';
563
- 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>`;
564
- }
565
-
566
- function startLifeRefresh() {
567
- if (lifeRefreshTimer) return;
568
- lifeRefreshTimer = setInterval(refreshLife, 3000);
585
+ /* ------------------------------- 脚本监管 ------------------------------- */
586
+ let lifeRefreshTimer = null;
587
+ let scriptLogTimer = null;
588
+ let currentScriptLog = null;
589
+ const scriptSelection = {
590
+ life: { kind: null, name: null },
591
+ toy: { kind: null, name: null },
592
+ };
593
+
594
+ function selectScriptSpace(space) {
595
+ document.querySelectorAll('[data-script-space]').forEach((button) => {
596
+ const active = button.dataset.scriptSpace === space;
597
+ button.classList.toggle('active', active);
598
+ button.setAttribute('aria-selected', String(active));
599
+ });
600
+ $('#script-space-life').classList.toggle('hidden', space !== 'life');
601
+ $('#script-space-toy').classList.toggle('hidden', space !== 'toy');
602
+ }
603
+
604
+ function selectAssetKind(group, kind) {
605
+ const space = $(`#script-space-${group}`);
606
+ space.querySelectorAll('[data-asset-kind]').forEach((button) => {
607
+ const active = button.dataset.assetKind === kind;
608
+ button.classList.toggle('active', active);
609
+ button.setAttribute('aria-selected', String(active));
610
+ });
611
+ space.querySelectorAll('[data-asset-panel]').forEach((panel) => {
612
+ panel.classList.toggle('hidden', panel.dataset.assetPanel !== kind);
613
+ });
614
+ }
615
+
616
+ async function showFirstLog(group) {
617
+ if (scriptSelection[group].name || window.matchMedia('(max-width: 700px)').matches) return;
618
+ const attribute = group === 'life' ? 'data-log' : 'data-toylog';
619
+ const first = $(`#${group}-logs button[${attribute}]`);
620
+ if (first) await showScriptLog(group, first.getAttribute(attribute));
621
+ }
622
+
623
+ function resetInspector(group) {
624
+ scriptSelection[group] = { kind: null, name: null };
625
+ $(`#${group}-inspector-kind`).textContent = 'PREVIEW';
626
+ $(`#${group}-inspector-title`).textContent = '选择一条日志或脚本';
627
+ $(`#${group}-inspector-state`).textContent = '日志打开后自动追踪更新';
628
+ $(`#${group}-preview-empty`).classList.remove('hidden');
629
+ $(`#${group}-source`).classList.add('hidden');
630
+ $(`#${group}-log-body`).classList.add('hidden');
631
+ }
632
+
633
+ function syncSelectedResource(group) {
634
+ const selected = scriptSelection[group];
635
+ $(`#script-space-${group}`).querySelectorAll('[data-resource-kind]').forEach((button) => {
636
+ button.classList.toggle('active', button.dataset.resourceKind === selected.kind && button.dataset.resourceName === selected.name);
637
+ });
638
+ }
639
+
640
+ function showInspector(group, kind, name, text, live = false) {
641
+ scriptSelection[group] = { kind, name };
642
+ const isLog = kind === 'log';
643
+ $(`#${group}-inspector-kind`).textContent = isLog ? 'LOG OUTPUT' : 'SOURCE CODE';
644
+ $(`#${group}-inspector-title`).textContent = name;
645
+ $(`#${group}-inspector-state`).textContent = isLog && live ? '实时追踪中 · 每 2 秒更新' : (isLog ? '运行日志' : '只读源码');
646
+ $(`#${group}-preview-empty`).classList.add('hidden');
647
+ const source = $(`#${group}-source`);
648
+ const log = $(`#${group}-log-body`);
649
+ source.classList.toggle('hidden', isLog);
650
+ log.classList.toggle('hidden', !isLog);
651
+ (isLog ? log : source).textContent = text;
652
+ syncSelectedResource(group);
653
+ if (window.matchMedia('(max-width: 700px)').matches) {
654
+ $(`#script-space-${group} .inspector-panel`).scrollIntoView({ behavior: 'smooth', block: 'start' });
655
+ }
656
+ }
657
+
658
+ async function fetchScriptText(url) {
659
+ const response = await fetch(url);
660
+ const text = await response.text();
661
+ if (!response.ok) {
662
+ try { throw new Error(JSON.parse(text).error || `HTTP ${response.status}`); }
663
+ catch (err) { if (err instanceof SyntaxError) throw new Error(`HTTP ${response.status}`); throw err; }
664
+ }
665
+ return text;
666
+ }
667
+
668
+ function startScriptLogPolling() {
669
+ if (scriptLogTimer) return;
670
+ scriptLogTimer = setInterval(async () => {
671
+ if (!currentScriptLog || lifeView.classList.contains('hidden')) return;
672
+ const { group, name } = currentScriptLog;
673
+ const area = group === 'life' ? 'life' : 'toys';
674
+ try {
675
+ const text = await fetchScriptText(`/api/me/roles/${lifeRoleId}/${area}/log/${encodeURIComponent(name)}`);
676
+ if (currentScriptLog?.group === group && currentScriptLog?.name === name) $(`#${group}-log-body`).textContent = text;
677
+ } catch { /* 单次刷新失败忽略,下一轮再试 */ }
678
+ }, 2000);
679
+ }
680
+
681
+ function stopScriptLogPolling() {
682
+ if (scriptLogTimer) { clearInterval(scriptLogTimer); scriptLogTimer = null; }
683
+ currentScriptLog = null;
684
+ }
685
+
686
+ async function showScriptLog(group, name) {
687
+ const area = group === 'life' ? 'life' : 'toys';
688
+ try {
689
+ const text = await fetchScriptText(`/api/me/roles/${lifeRoleId}/${area}/log/${encodeURIComponent(name)}`);
690
+ selectScriptSpace(group);
691
+ selectAssetKind(group, 'logs');
692
+ currentScriptLog = { group, name };
693
+ showInspector(group, 'log', name, text, true);
694
+ startScriptLogPolling();
695
+ } catch (err) { status(err.message, true); }
696
+ }
697
+
698
+ async function showScriptSource(group, name) {
699
+ const area = group === 'life' ? 'life' : 'toys';
700
+ try {
701
+ const text = await fetchScriptText(`/api/me/roles/${lifeRoleId}/${area}/script/${encodeURIComponent(name)}`);
702
+ if (currentScriptLog?.group === group) currentScriptLog = null;
703
+ selectScriptSpace(group);
704
+ selectAssetKind(group, 'scripts');
705
+ showInspector(group, 'source', name, text);
706
+ } catch (err) { status(err.message, true); }
707
+ }
708
+
709
+ function resourceButton(group, kind, name, attribute) {
710
+ const active = scriptSelection[group].kind === kind && scriptSelection[group].name === name ? ' active' : '';
711
+ 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>`;
712
+ }
713
+
714
+ function startLifeRefresh() {
715
+ if (lifeRefreshTimer) return;
716
+ lifeRefreshTimer = setInterval(refreshLife, 3000);
569
717
  }
570
718
  function stopLifeRefresh() {
571
719
  if (lifeRefreshTimer) { clearInterval(lifeRefreshTimer); lifeRefreshTimer = null; }
572
720
  }
573
- async function openLife(rid) {
574
- lifeRoleId = rid;
575
- const role = roles.find((r) => r.roleId === rid);
721
+ async function openLife(rid) {
722
+ lifeRoleId = rid;
723
+ const role = roles.find((r) => r.roleId === rid);
576
724
  $('#life-role-name').textContent = role?.persona?.name || '未命名角色';
577
- rolesView.classList.add('hidden');
578
- editorView.classList.add('hidden');
579
- lifeView.classList.remove('hidden');
580
- pageTitle.textContent = '脚本监管';
581
- selectScriptSpace('life');
582
- selectAssetKind('life', 'logs');
583
- selectAssetKind('toy', 'logs');
584
- resetInspector('life');
585
- resetInspector('toy');
586
- stopScriptLogPolling();
587
- lifeView.scrollIntoView({ behavior: 'smooth', block: 'start' });
588
- await refreshLife();
589
- await showFirstLog('life');
590
- startLifeRefresh();
725
+ rolesView.classList.add('hidden');
726
+ editorView.classList.add('hidden');
727
+ lifeView.classList.remove('hidden');
728
+ pageTitle.textContent = '脚本监管';
729
+ selectScriptSpace('life');
730
+ selectAssetKind('life', 'logs');
731
+ selectAssetKind('toy', 'logs');
732
+ resetInspector('life');
733
+ resetInspector('toy');
734
+ stopScriptLogPolling();
735
+ lifeView.scrollIntoView({ behavior: 'smooth', block: 'start' });
736
+ await refreshLife();
737
+ await showFirstLog('life');
738
+ startLifeRefresh();
591
739
  }
592
740
  function fmtDur(ms) {
593
741
  const s = Math.max(0, Math.floor(ms / 1000));
@@ -599,10 +747,10 @@ function fmtDur(ms) {
599
747
  async function refreshLife() {
600
748
  const data = await api(`/api/me/roles/${lifeRoleId}/life`);
601
749
  $('#life-manifest').textContent = JSON.stringify(data.manifest || {}, null, 2);
602
- // 运行中脚本(dsh 用 life_run 启动;由脚本自己决定何时结束,插件只监管)
603
- const running = data.running || [];
604
- $('#life-running-count').textContent = `${running.length} 个运行中`;
605
- $('#life-running').innerHTML = running.length
750
+ // 运行中脚本(dsh 用 life_run 启动;由脚本自己决定何时结束,插件只监管)
751
+ const running = data.running || [];
752
+ $('#life-running-count').textContent = `${running.length} 个运行中`;
753
+ $('#life-running').innerHTML = running.length
606
754
  ? running.map((r) => `<div class="run-row">
607
755
  <span class="run-info">${esc(r.scriptName)} · PID ${esc(r.pid)} · 已运行 ${fmtDur(r.elapsedMs)}</span>
608
756
  <button class="ghost run-log" data-log="${esc(r.logName)}">日志</button>
@@ -610,58 +758,58 @@ async function refreshLife() {
610
758
  </div>`).join('')
611
759
  : '<div class="muted">没有脚本在运行(dsh 用 life_run 启动,可长驻循环)</div>';
612
760
  // 脚本清单(点击查看源码)
613
- const scripts = Object.keys(data.manifest?.scripts || {});
614
- $('#life-script-count').textContent = scripts.length;
615
- $('#life-scripts').innerHTML = scripts.length
616
- ? scripts.map((n) => resourceButton('life', 'source', n, 'data-script')).join('')
617
- : '<div class="muted">life/ 下还没有脚本</div>';
618
- $('#life-backup-count').textContent = (data.backups || []).length;
619
- $('#life-backups').innerHTML = (data.backups || []).length
620
- ? data.backups.map((b) => `<div class="backup-item" title="${esc(b)}">${esc(b)}</div>`).join('')
621
- : '<div class="muted">暂无备份</div>';
622
- const logs = $('#life-logs');
623
- $('#life-log-count').textContent = (data.logs || []).length;
624
- logs.innerHTML = (data.logs || []).length
625
- ? data.logs.map((n) => resourceButton('life', 'log', n, 'data-log')).join('')
626
- : '<div class="muted">还没有运行日志</div>';
627
- // 玩具操控脚本(toys/)
761
+ const scripts = Object.keys(data.manifest?.scripts || {});
762
+ $('#life-script-count').textContent = scripts.length;
763
+ $('#life-scripts').innerHTML = scripts.length
764
+ ? scripts.map((n) => resourceButton('life', 'source', n, 'data-script')).join('')
765
+ : '<div class="muted">life/ 下还没有脚本</div>';
766
+ $('#life-backup-count').textContent = (data.backups || []).length;
767
+ $('#life-backups').innerHTML = (data.backups || []).length
768
+ ? data.backups.map((b) => `<div class="backup-item" title="${esc(b)}">${esc(b)}</div>`).join('')
769
+ : '<div class="muted">暂无备份</div>';
770
+ const logs = $('#life-logs');
771
+ $('#life-log-count').textContent = (data.logs || []).length;
772
+ logs.innerHTML = (data.logs || []).length
773
+ ? data.logs.map((n) => resourceButton('life', 'log', n, 'data-log')).join('')
774
+ : '<div class="muted">还没有运行日志</div>';
775
+ // 设备脚本(device-scripts/ 与兼容 toys/)
628
776
  try {
629
- const t = await api(`/api/me/roles/${lifeRoleId}/toys`);
630
- $('#toy-running-count').textContent = `${(t.running || []).length} 个运行中`;
631
- $('#toy-running').innerHTML = (t.running || []).length
632
- ? 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('')
633
- : '<div class="muted">没有玩具脚本在运行(dsh 用 toy_run_script 运行)</div>';
634
- $('#toy-script-count').textContent = (t.scripts || []).length;
635
- $('#toy-scripts').innerHTML = (t.scripts || []).length
636
- ? t.scripts.map((n) => resourceButton('toy', 'source', n, 'data-toyscript')).join('')
637
- : '<div class="muted">toys/ 下还没有脚本</div>';
638
- $('#toy-log-count').textContent = (t.logs || []).length;
639
- $('#toy-logs').innerHTML = (t.logs || []).length
640
- ? t.logs.map((n) => resourceButton('toy', 'log', n, 'data-toylog')).join('')
641
- : '<div class="muted">还没有玩具运行日志</div>';
642
- } catch { /* 老版本无 toys 端点时忽略 */ }
643
- }
644
- document.querySelectorAll('[data-script-space]').forEach((button) => button.addEventListener('click', async () => {
645
- const group = button.dataset.scriptSpace;
646
- selectScriptSpace(group);
647
- await showFirstLog(group);
648
- const selected = scriptSelection[group];
649
- currentScriptLog = selected.kind === 'log' ? { group, name: selected.name } : null;
650
- }));
651
- document.querySelectorAll('[data-asset-kind]').forEach((button) => button.addEventListener('click', () => selectAssetKind(button.dataset.assetGroup, button.dataset.assetKind)));
652
- $('#life-logs').addEventListener('click', async (e) => {
653
- const btn = e.target.closest('button[data-log]');
654
- if (!btn) return;
655
- await showScriptLog('life', btn.dataset.log);
656
- });
657
- $('#life-scripts').addEventListener('click', async (e) => {
658
- const btn = e.target.closest('button[data-script]');
659
- if (!btn) return;
660
- await showScriptSource('life', btn.dataset.script);
661
- });
662
- $('#life-running').addEventListener('click', async (e) => {
663
- const logBtn = e.target.closest('button.run-log');
664
- if (logBtn) { await showScriptLog('life', logBtn.dataset.log); return; }
777
+ const t = await api(`/api/me/roles/${lifeRoleId}/toys`);
778
+ $('#toy-running-count').textContent = `${(t.running || []).length} 个运行中`;
779
+ $('#toy-running').innerHTML = (t.running || []).length
780
+ ? 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('')
781
+ : '<div class="muted">没有设备脚本在运行;使用对应驱动 skill 中的脚本入口</div>';
782
+ $('#toy-script-count').textContent = (t.scripts || []).length;
783
+ $('#toy-scripts').innerHTML = (t.scripts || []).length
784
+ ? t.scripts.map((n) => resourceButton('toy', 'source', n, 'data-toyscript')).join('')
785
+ : '<div class="muted">toys/ 下还没有脚本</div>';
786
+ $('#toy-log-count').textContent = (t.logs || []).length;
787
+ $('#toy-logs').innerHTML = (t.logs || []).length
788
+ ? t.logs.map((n) => resourceButton('toy', 'log', n, 'data-toylog')).join('')
789
+ : '<div class="muted">还没有设备运行日志</div>';
790
+ } catch { /* 老版本无 toys 端点时忽略 */ }
791
+ }
792
+ document.querySelectorAll('[data-script-space]').forEach((button) => button.addEventListener('click', async () => {
793
+ const group = button.dataset.scriptSpace;
794
+ selectScriptSpace(group);
795
+ await showFirstLog(group);
796
+ const selected = scriptSelection[group];
797
+ currentScriptLog = selected.kind === 'log' ? { group, name: selected.name } : null;
798
+ }));
799
+ document.querySelectorAll('[data-asset-kind]').forEach((button) => button.addEventListener('click', () => selectAssetKind(button.dataset.assetGroup, button.dataset.assetKind)));
800
+ $('#life-logs').addEventListener('click', async (e) => {
801
+ const btn = e.target.closest('button[data-log]');
802
+ if (!btn) return;
803
+ await showScriptLog('life', btn.dataset.log);
804
+ });
805
+ $('#life-scripts').addEventListener('click', async (e) => {
806
+ const btn = e.target.closest('button[data-script]');
807
+ if (!btn) return;
808
+ await showScriptSource('life', btn.dataset.script);
809
+ });
810
+ $('#life-running').addEventListener('click', async (e) => {
811
+ const logBtn = e.target.closest('button.run-log');
812
+ if (logBtn) { await showScriptLog('life', logBtn.dataset.log); return; }
665
813
  const btn = e.target.closest('button[data-run]');
666
814
  if (!btn) return;
667
815
  try {
@@ -670,39 +818,39 @@ $('#life-running').addEventListener('click', async (e) => {
670
818
  await refreshLife();
671
819
  } catch (err) { status(err.message, true); }
672
820
  });
673
- $('#toy-running').addEventListener('click', async (e) => {
674
- const logBtn = e.target.closest('button.toy-run-log');
675
- if (logBtn) { await showScriptLog('toy', logBtn.dataset.toylog); return; }
676
- const btn = e.target.closest('button.toy-stop');
821
+ $('#toy-running').addEventListener('click', async (e) => {
822
+ const logBtn = e.target.closest('button.toy-run-log');
823
+ if (logBtn) { await showScriptLog('toy', logBtn.dataset.toylog); return; }
824
+ const btn = e.target.closest('button.toy-stop');
677
825
  if (!btn) return;
678
826
  try {
679
827
  const r = await api(`/api/me/roles/${lifeRoleId}/toys/stop`, 'POST', { runId: btn.dataset.run });
680
- status(r.ok ? '已终止玩具脚本' : (r.error || '终止失败'), !r.ok);
828
+ status(r.ok ? '已终止设备脚本' : (r.error || '终止失败'), !r.ok);
681
829
  await refreshLife();
682
830
  } catch (err) { status(err.message, true); }
683
831
  });
684
- $('#toy-logs').addEventListener('click', async (e) => {
685
- const btn = e.target.closest('button[data-toylog]');
686
- if (!btn) return;
687
- await showScriptLog('toy', btn.dataset.toylog);
688
- });
689
- $('#toy-scripts').addEventListener('click', async (e) => {
690
- const btn = e.target.closest('button[data-toyscript]');
691
- if (!btn) return;
692
- await showScriptSource('toy', btn.dataset.toyscript);
693
- });
694
- $('#btn-close-life').addEventListener('click', () => { stopScriptLogPolling(); stopLifeRefresh(); showRoles(); });
832
+ $('#toy-logs').addEventListener('click', async (e) => {
833
+ const btn = e.target.closest('button[data-toylog]');
834
+ if (!btn) return;
835
+ await showScriptLog('toy', btn.dataset.toylog);
836
+ });
837
+ $('#toy-scripts').addEventListener('click', async (e) => {
838
+ const btn = e.target.closest('button[data-toyscript]');
839
+ if (!btn) return;
840
+ await showScriptSource('toy', btn.dataset.toyscript);
841
+ });
842
+ $('#btn-close-life').addEventListener('click', () => { stopScriptLogPolling(); stopLifeRefresh(); showRoles(); });
695
843
 
696
844
  /* ------------------------------- 表情包管理 ------------------------------- */
697
- async function openMemes(rid) {
845
+ async function openMemes(rid) {
698
846
  memeRoleId = rid;
699
847
  const role = roles.find((r) => r.roleId === rid);
700
848
  $('#meme-role-name').textContent = role?.persona?.name || '未命名角色';
701
- rolesView.classList.add('hidden');
702
- editorView.classList.add('hidden');
849
+ rolesView.classList.add('hidden');
850
+ editorView.classList.add('hidden');
703
851
  lifeView.classList.add('hidden');
704
- memeView.classList.remove('hidden');
705
- pageTitle.textContent = '表情包库';
852
+ memeView.classList.remove('hidden');
853
+ pageTitle.textContent = '表情包库';
706
854
  memeView.scrollIntoView({ behavior: 'smooth' });
707
855
  await loadMemes();
708
856
  }
@@ -777,7 +925,7 @@ function bytesToBase64(bytes) {
777
925
  for (const b of bytes) bin += String.fromCharCode(b);
778
926
  return btoa(bin);
779
927
  }
780
- $('#btn-close-meme').addEventListener('click', showRoles);
928
+ $('#btn-close-meme').addEventListener('click', showRoles);
781
929
 
782
930
  /* ------------------------------- 启动 ------------------------------- */
783
931
  setAuthMode();
@@ -790,3 +938,15 @@ setAuthMode();
790
938
  show('auth');
791
939
  }
792
940
  })();
941
+
942
+ // 静态配置也复用同一说明入口,details 同时支持鼠标、触屏和键盘。
943
+ for (const [selector,text] of Object.entries({
944
+ '#f-channel-adapter':'每个角色使用一个通信连接和一个绑定聊天对象。切换实现不会自动认领旧身份。',
945
+ '#f-chatwindow':'距用户最后一条消息不足此窗口时,一般后台唤醒会推迟;设备的高优先级结束事件除外。',
946
+ '#f-voice-provider':'只填写所选语音实现声明的字段;不支持声音克隆的服务无需上传参考音频。',
947
+ '#device-driver':'设备的能力、连接和脚本用法由驱动及配套 skill 共同提供,不通用假设激活或停止。',
948
+ '#f-roleplay-enabled':'开启后由独立角色会话生成最终消息,主会话负责事实、工具与调度。',
949
+ '#f-roleplay-input':'角色会话的输入活动预算,超过后换段并补齐基础材料;不是回复输出限制。',
950
+ '#f-meme-enabled':'仅控制周期收集;已收到图片的识别和整理另按现有维护流程进行。',
951
+ '#f-meme-vision-model':'图片理解只使用本角色配置的模型;没有可用视觉能力时不会借用其他账号或宿主默认模型。',
952
+ })) fieldHelp($(selector)?.closest('label'),text);